package com.yida.gwj.deposit.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.yida.common.core.constant.SecurityConstants;
import com.yida.common.core.domain.R;
import com.yida.common.core.exception.ServiceException;
import com.yida.common.core.text.Convert;
import com.yida.common.core.utils.CheckRemoteServiceResultUtils;
import com.yida.common.core.utils.DateUtils;
import com.yida.common.core.utils.StringUtils;
import com.yida.common.core.utils.poi.ExcelUtil;
import com.yida.common.redis.service.RedisService;
import com.yida.common.security.utils.SecurityUtils;
import com.yida.gwj.api.domain.*;
import com.yida.gwj.api.service.RemoteGwjConfigService;
import com.yida.gwj.api.service.RemoteGwjFinanceService;
import com.yida.gwj.common.constant.GwjCacheConstants;
import com.yida.gwj.common.constant.GwjConstants;
import com.yida.gwj.common.constant.GwjCustomImportConstants;
import com.yida.gwj.common.constant.GwjRemarkConstants;
import com.yida.gwj.common.domain.GwjBaseBusinessNum;
import com.yida.gwj.common.domain.*;
import com.yida.gwj.common.enums.*;
import com.yida.gwj.common.service.*;
import com.yida.gwj.common.utils.GwjCalculateFormulaUtil;
import com.yida.gwj.common.utils.GwjConvertUtil;
import com.yida.gwj.deposit.domain.*;
import com.yida.gwj.deposit.domain.dto.split.GwjAllocatedAmountDTO;
import com.yida.gwj.deposit.domain.dto.split.GwjAllocatedAmountScreeningDTO;
import com.yida.gwj.deposit.domain.dto.split.GwjFundsSplitBusinessHouseDTO;
import com.yida.gwj.deposit.domain.dto.split.GwjFundsSplitHouseholdRecordHeadDTO;
import com.yida.gwj.deposit.domain.request.GwjCalculateRequest;
import com.yida.gwj.deposit.domain.request.GwjPublicAccountRequest;
import com.yida.gwj.deposit.domain.request.GwjPublicBusinessHouseRequest;
import com.yida.gwj.deposit.domain.request.split.GwjAllocatedAmountRequest;
import com.yida.gwj.deposit.domain.request.split.GwjFundsSplitBusinessHouseRequest;
import com.yida.gwj.deposit.domain.request.split.GwjFundsSplitSaveSubmitRequest;
import com.yida.gwj.deposit.domain.vo.GwjDepositBusinessHouseExcelVo;
import com.yida.gwj.deposit.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 维修资金分户（初始化）（缴存业务管理模块）Service业务层处理
 *
 * @author lqq
 * @date 2023-01-10
 */
@Service
public class GwjFundsSplitBusinessServiceImpl implements IGwjFundsSplitBusinessService {
    private final Logger log = LoggerFactory.getLogger(GwjFundsSplitBusinessServiceImpl.class);

    @Resource
    private IGwjDepositBusinessLogService gwjDepositBusinessLogService;

    @Resource
    private IGwjDepositBusinessService gwjDepositBusinessService;

    @Resource
    private IGwjDepositBusinessMoneyService gwjDepositBusinessMoneyService;

    @Resource
    private IGwjDepositBusinessCommunityService gwjDepositBusinessCommunityService;

    @Resource
    private IGwjDepositBusinessBuildService gwjDepositBusinessBuildService;

    @Resource
    private IGwjDepositBusinessHouseService gwjDepositBusinessHouseService;

    @Resource
    private IGwjDepositBusinessOwnerService gwjDepositBusinessOwnerService;

    @Resource
    private IGwjDepositBusinessDetailService gwjDepositBusinessDetailService;

    @Resource
    private IGwjBaseBusinessNumService businessNumService;

    @Resource
    private IGwjBaseBuildService buildService;

    @Resource
    private IGwjBaseHouseService houseService;

    @Resource
    private IGwjBaseOwnerService ownerService;

    @Resource
    private IGwjImpSqeService gwjImpSqeService;

    @Resource
    private RedisService redisService;

    @Resource
    private RemoteGwjConfigService remoteGwjConfigService;

    @Resource
    private RemoteGwjFinanceService remoteGwjFinanceService;

    /**
     * 维修资金分户（初始化）（保存）
     *
     * @param saveSubmitRequest 请求参数
     * @return /
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveBusiness(GwjFundsSplitSaveSubmitRequest saveSubmitRequest) {
        // 获取参数
        GwjDepositBusiness business = GwjConvertUtil.convert(saveSubmitRequest.getBusiness(), GwjDepositBusiness.class);
        GwjDepositBusinessMoney money = GwjConvertUtil.convert(saveSubmitRequest.getBusinessMoney(), GwjDepositBusinessMoney.class);
        GwjDepositBusinessCommunity community = GwjConvertUtil.convert(saveSubmitRequest.getBusinessCommunity(), GwjDepositBusinessCommunity.class);
        List<GwjDepositBusinessBuild> builds = GwjConvertUtil.convertList(saveSubmitRequest.getBusinessBuilds(), GwjDepositBusinessBuild.class);
        List<GwjDepositBusinessDetail> details = GwjConvertUtil.convertList(saveSubmitRequest.getMoneyDetails(), GwjDepositBusinessDetail.class);
        // ===============================================处理业务参数=======================================
        // 设置业务流程
        R<GwjConfBusinessFlag> gwjConfBusinessFlagR = remoteGwjConfigService.selectGwjConfBusinessFlagByBizFlagId(business.getBizFlagId(), SecurityConstants.INNER);
        if (!CheckRemoteServiceResultUtils.isSuccessWithData(gwjConfBusinessFlagR)) {
            throw new ServiceException("业务流程查询失败");
        }
        business.setFlowId(gwjConfBusinessFlagR.getData().getFlowId());
        // 设置地区
        business.setAreaId(community.getAreaId());
        try {
            GwjBaseBusinessNum businessNum = businessNumService.getNextNum(business.getAreaId(), business.getBizFlagId());
            // 设置业务编号
            business.setBizNum(Convert.toLong(businessNum.toString()));
        } catch (Exception e) {
            log.error("资金分户初始化生成业务编码失败-> [{}]", e);
            throw new ServiceException("资金分户初始化生成业务编码失败");
        }
        // 设置差额
        business.setLackMoney(money.getTotalMoney());
        // 保存业务
        if (1 != gwjDepositBusinessService.insertGwjDepositBusiness(business)) {
            throw new ServiceException("资金分户初始化保存业务失败");
        }

        // ===============================================处理业务金额参数=======================================
        // 修改分户数据金额,设置已选、业务ID、业务编码
        details.forEach(detail -> {
            R<GwjFinanceMoney> gwjFinanceMoneyR = remoteGwjFinanceService.selectFinanceMoneyByMoneyId(detail.getMoneyId(), SecurityConstants.INNER);
            if (!CheckRemoteServiceResultUtils.isSuccessWithData(gwjFinanceMoneyR)) {
                throw new ServiceException("资金分户初始化分户数据金额查询失败");
            }
            GwjFinanceMoney gwjFinanceMoney = gwjFinanceMoneyR.getData();
            if (StringUtils.equals(gwjFinanceMoney.getSelectFlag(), GwjBusinessHouseStatus.CONFIRM.getCode())) {
                throw new ServiceException("资金分户初始化分户数据金额已被选择，请核实（" + gwjFinanceMoney.getDepositMoney() + "）");
            }
            gwjFinanceMoney.setSelectFlag(GwjBusinessHouseStatus.CONFIRM.getCode());
            gwjFinanceMoney.setBizId(business.getBizId());
            gwjFinanceMoney.setBizNum(business.getBizNum());
            if (CheckRemoteServiceResultUtils.isCodeFail(remoteGwjFinanceService.updateFinanceMoney(gwjFinanceMoney, SecurityConstants.INNER))) {
                throw new ServiceException("资金分户初始化分户数据金额更新失败");
            }
            // ===============================================处理业务金额参数=======================================
            // 设置业务编号和业务ID
            detail.setBizId(business.getBizId());
            detail.setBizNum(business.getBizNum());
            if (1 != gwjDepositBusinessDetailService.insertGwjDepositBusinessDetail(detail)) {
                throw new ServiceException("资金分户初始化保存业务金额失败");
            }
        });
        // gwjDepositBusinessDetailService.insertBatchGwjDepositBusinessDetail(details);
        // ===============================================处理业务小区参数=======================================
        // 设置业务ID
        community.setBizId(business.getBizId());
        // 保存小区信息
        if (1 != gwjDepositBusinessCommunityService.insertGwjDepositBusinessCommunity(community)) {
            throw new ServiceException("资金分户初始化保存业务小区失败");
        }

        // ===============================================处理业务楼栋参数=======================================
        builds.forEach(build -> {
            build.setBizId(community.getBizId());
            build.setAreaId(community.getAreaId());
            build.setStreetId(community.getStreetId());
            build.setBizCommunityId(community.getBizCommunityId());
            build.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getRealName());
            build.setCreateTime(DateUtils.getNowDate());
            if (!StringUtils.equals(GwjConstants.YES, build.getPublicFlag())) {
                build.setPublicFlag(GwjConstants.NO);
            }
        });
        // 保存业务楼栋信息
        if (0 == gwjDepositBusinessBuildService.insertGwjDepositBusinessBuilds(builds)) {
            throw new ServiceException("资金分户初始化保存业务楼栋失败");
        }

        // ===============================================处理业务房屋参数========================================
        // 查询基础房屋数据
        String[] buildCodes = builds.stream().map(GwjBaseBusinessBuild::getBuildCode).toArray(String[]::new);
        List<GwjBaseHouse> houses = houseService.selectGwjBaseListByBuildCodesAndAreaId(buildCodes, community.getAreaId());
        // 基础房屋数据不为空
        BigDecimal totalSize = BigDecimal.ZERO;
        if (StringUtils.isNotEmpty(houses)) {
            List<GwjDepositBusinessHouse> businessHouses = GwjConvertUtil.convertList(houses, GwjDepositBusinessHouse.class);
            // 保存业务房屋数据
            for (GwjDepositBusinessHouse businessHouse : businessHouses) {
                businessHouse.setBizId(community.getBizId());
                businessHouse.setAreaId(community.getAreaId());
                businessHouse.setStreetId(community.getStreetId());
                businessHouse.setDepositSize(BigDecimal.ZERO);
                businessHouse.setDepositMoney(BigDecimal.ZERO);
                businessHouse.setLackMoney(BigDecimal.ZERO);
                businessHouse.setDepositTime(null);
                businessHouse.setSelectFlag(GwjBusinessHouseStatus.CONFIRM.getCode());
                businessHouse.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getRealName());
                businessHouse.setCreateTime(DateUtils.getNowDate());
                if (!StringUtils.equals(GwjConstants.YES, businessHouse.getPublicFlag())) {
                    businessHouse.setPublicFlag(GwjConstants.NO);
                }
                totalSize = totalSize.add(businessHouse.getActualSize());
            }
            if (0 == gwjDepositBusinessHouseService.insertGwjDepositBusinessHouses(businessHouses)) {
                throw new ServiceException("资金分户初始化保存业务房屋失败");
            }

            // ===============================================处理业务业主参数========================================
            // 查询基础业主数据
            List<String> houseCodes = businessHouses.stream().map(GwjBaseBusinessHouse::getHouseCode).collect(Collectors.toList());
            // 分段查询 10个位一组
            List<List<String>> codeList = GwjConvertUtil.partition(houseCodes, 10);
            for (List<String> list : codeList) {
                // 查询基础业主数据
                List<GwjBaseOwner> owners = ownerService.selectGwjBaseListByGwjBaseHouseCodes(list.toArray(new String[0]), community.getAreaId());
                // 基础业主数据不为空
                if (StringUtils.isNotEmpty(owners)) {
                    List<GwjDepositBusinessOwner> businessOwners = GwjConvertUtil.convertList(owners, GwjDepositBusinessOwner.class);
                    businessOwners.forEach(owner -> {
                        owner.setBizId(community.getBizId());
                        owner.setAreaId(community.getAreaId());
                        owner.setStreetId(community.getStreetId());
                        owner.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getRealName());
                        owner.setCreateTime(DateUtils.getNowDate());
                    });
                    if (0 == gwjDepositBusinessOwnerService.insertBatchGwjDepositBusinessOwner(businessOwners)) {
                        throw new ServiceException("资金分户初始化保存业务业主失败");
                    }
                }
            }
            money.setTotalOwner(Convert.toLong(houses.size()));
        }

        // ===============================================保存金额信息========================================
        money.setBizId(business.getBizId());
        money.setLedgerType(GwjConstants.INCOME);
        money.setAreaId(community.getAreaId());
        money.setFactSize(totalSize);
        if (1 != gwjDepositBusinessMoneyService.insertGwjDepositBusinessMoney(money)) {
            throw new ServiceException("资金分户初始化保存业务金额失败");
        }
        // 日志
        gwjDepositBusinessLogService.addSaveLog(business);
        return business.getBizId();
    }

    /**
     * 维修资金分户（初始化）（保存修改）
     *
     * @param saveSubmitRequest 请求参数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBusiness(GwjFundsSplitSaveSubmitRequest saveSubmitRequest) {
        GwjDepositBusiness business = GwjConvertUtil.convert(saveSubmitRequest.getBusiness(), GwjDepositBusiness.class);
        List<GwjDepositBusinessBuild> builds = GwjConvertUtil.convertList(saveSubmitRequest.getBusinessBuilds(), GwjDepositBusinessBuild.class);
        // 检验当前登录账号是否有权限
        gwjDepositBusinessService.checkPermission(business.getBizId());
        business.setStatus(GwjBusinessStatus.NORMAL.getCode());
        if (1 != gwjDepositBusinessService.updateGwjDepositBusiness(business)) {
            throw new ServiceException("资金分户初始化更新业务信息失败");
        }
        // 更新楼栋数据
        gwjDepositBusinessBuildService.updateBatchGwjDepositBusinessBuild(builds);
        // 日志
        gwjDepositBusinessLogService.addSaveLog(business);
    }

    /**
     * 维修资金分户（初始化）（提交）
     *
     * @param saveSubmitRequest 请求参数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitBusiness(GwjFundsSplitSaveSubmitRequest saveSubmitRequest) {
        GwjDepositBusiness business = GwjConvertUtil.convert(saveSubmitRequest.getBusiness(), GwjDepositBusiness.class);
        GwjDepositBusinessLog businessLog = saveSubmitRequest.getBusinessLog();
        // 检验当前登录账号是否有权限
        if (StringUtils.isNull(business.getBizId())) {
            throw new ServiceException("请先保存业务");
        }
        gwjDepositBusinessService.checkPermission(business.getBizId());
        // 判断是否已有数据 可以直接提交
        if (StringUtils.isNull(gwjDepositBusinessCommunityService.selectGwjDepositBusinessCommunityListByBizId(business.getBizId()))) {
            throw new ServiceException("业务小区不能为空");
        }
        if (StringUtils.isEmpty(gwjDepositBusinessBuildService.selectGwjDepositBusinessBuildListByBizId(business.getBizId()))) {
            throw new ServiceException("业务楼栋不能为空");
        }
        // 判断当期步骤是否生成财务流水
        if (!checkStepConfigInfo(business.getStepId(), StepConfigInfoEnum.GENERATE_FINANCIAL_STATEMENT.getCode())) {
            // 查询总账流水
            R<List<GwjFinanceAccountMain>> gwjFinanceAccountMainsR = remoteGwjFinanceService.selectGwjFinanceAccountMainList(new GwjFinanceAccountMain() {
                {
                    setBizId(business.getBizId());
                }
            }, SecurityConstants.INNER);
            if (StringUtils.isEmpty(gwjFinanceAccountMainsR.getData())) {
                throw new ServiceException("当前业务步骤请先生成财务流水");
            }
        }
        // 判断当期步骤是否已完成财务对账
        if (!checkStepConfigInfo(business.getStepId(), StepConfigInfoEnum.FINANCE_CHECK.getCode())) {
            GwjDepositBusinessMoney gwjDepositBusinessMoney = gwjDepositBusinessMoneyService.selectGwjDepositBusinessMoneyByBizId(business.getBizId());
            if (StringUtils.isNull(gwjDepositBusinessMoney)) {
                throw new ServiceException("查无金额信息");
            }
            if (!StringUtils.equals(gwjDepositBusinessMoney.getStatus(), GwjCheckAccountStatus.CHECK_SUCCESS.getCode())) {
                throw new ServiceException("对账成功后才可以提交");
            }
        }
        // 设置日志流程步骤,业务编号
        businessLog.setStepId(business.getStepId());
        businessLog.setBizId(business.getBizId());
        // 获取当前步骤所有配置
        R<List<String>> configInfosR = remoteGwjConfigService.selectGwjConfStepConfigInfoCodeListByBizFlagId(businessLog.getStepId(), SecurityConstants.INNER);
        if (!CheckRemoteServiceResultUtils.isSuccessWithData(configInfosR)) {
            throw new ServiceException("当前步骤配置查询失败");
        }
        // 判断是否需要选收件人
        if (StringUtils.containsAny(configInfosR.getData(), StepConfigInfoEnum.SUBMIT_CHOOSE_USER.getCode()) && StringUtils.isAnyBlank(Convert.toStr(businessLog.getUserId()), businessLog.getRealName())) {
            throw new ServiceException("请选择下一位收件人");
        }
        // 当前办理人员
        business.setCurrentOperId(StringUtils.isNull(businessLog.getUserId()) ? SecurityUtils.getUserId() : businessLog.getUserId());
        business.setCurrentOperName(StringUtils.isBlank(businessLog.getRealName()) ? SecurityUtils.getLoginUser().getSysUser().getRealName() : businessLog.getRealName());
        // 当前步骤
        R<GwjConfStep> nextStepR = remoteGwjConfigService.selectNextGwjConfStepByFlagId(GwjBusinessFlagType.FUNDS_SPLIT.getCode(), business.getStepId(), SecurityConstants.INNER);
        if (!CheckRemoteServiceResultUtils.isSuccessWithData(nextStepR)) {
            throw new ServiceException("下一个步骤查询失败");
        }
        GwjConfStep nextStep = nextStepR.getData();
        business.setStepId(nextStep.getStepId());
        // 更新业务
        business.setStatus(GwjBusinessStatus.NORMAL.getCode());
        // 日志
        gwjDepositBusinessLogService.addSubmitLog(businessLog, business);
        // 判断是不是已经最后一步
        R<GwjConfStep> finallyStepR = remoteGwjConfigService.selectNextGwjConfStepByFlagId(GwjBusinessFlagType.FUNDS_SPLIT.getCode(), nextStep.getStepId(), SecurityConstants.INNER);
        if (CheckRemoteServiceResultUtils.isCodeFail(finallyStepR)) {
            throw new ServiceException("下一个步骤查询失败");
        }
        if (StringUtils.isNull(finallyStepR.getData())) {
            // 将业务数据更新基础数据
            // 已选择房屋数据
            List<GwjDepositBusinessHouse> gwjDepositBusinessHouses = gwjDepositBusinessHouseService.selectGwjDepositBusinessHouseListByBizIdAndSelectFlag(business.getBizId(), GwjBusinessHouseStatus.CONFIRM.getCode());
            if (StringUtils.isNotEmpty(gwjDepositBusinessHouses)) {
                gwjDepositBusinessHouses.forEach(gwjDepositBusinessHouse -> {
                    // 公用户做插入
                    if (StringUtils.equals(gwjDepositBusinessHouse.getPublicFlag(), GwjConstants.YES)) {
                        // 判断所属楼栋是不是也是公用户
                        GwjDepositBusinessBuild gwjDepositBusinessBuild = gwjDepositBusinessBuildService.selectGwjDepositBusinessBuildListByBizIdAndBuildCode(business.getBizId(), gwjDepositBusinessHouse.getBuildCode());
                        if (StringUtils.isNotNull(gwjDepositBusinessBuild) && StringUtils.equals(gwjDepositBusinessBuild.getPublicFlag(), GwjConstants.YES)) {
                            // 判断基础库是否已存在
                            if (StringUtils.isNull(gwjDepositBusinessBuild.getBuildId())) {
                                // 查询小区
                                GwjDepositBusinessCommunity businessCommunity = gwjDepositBusinessCommunityService.selectGwjDepositBusinessCommunityByBizId(business.getBizId());
                                // 插入
                                GwjBaseBuild baseBuild = GwjConvertUtil.convert(gwjDepositBusinessBuild, GwjBaseBuild.class);
                                baseBuild.setCommunityId(businessCommunity.getCommunityId());
                                if (1 != buildService.insertGwjBaseBuild(baseBuild)) {
                                    throw new ServiceException("资金分户初始化保存公用户楼栋失败");
                                }
                            }
                        }
                        // 判断公用户房屋是否已存在
                        if (StringUtils.isNotNull(gwjDepositBusinessHouse.getHouseId())) {
                            GwjBaseHouse baseHouse = houseService.selectGwjBaseHouseByGwjBaseHouseId(gwjDepositBusinessHouse.getHouseId());
                            if (StringUtils.isNull(baseHouse)) {
                                throw new ServiceException("资金分户初始化查询基础房屋失败");
                            }
                            // 累计金额
                            baseHouse.setDepositMoney(StringUtils.isNull(baseHouse.getDepositMoney()) ? BigDecimal.ZERO : baseHouse.getDepositMoney().add(gwjDepositBusinessHouse.getDepositMoney()));
                            baseHouse.setCurrentMoney(StringUtils.isNull(baseHouse.getCurrentMoney()) ? BigDecimal.ZERO : baseHouse.getCurrentMoney().add(gwjDepositBusinessHouse.getDepositMoney()));
                            if (0 == houseService.updateGwjBaseHouse(baseHouse)) {
                                throw new ServiceException("资金分户初始化更新公用户房屋失败");
                            }
                        } else {
                            GwjBaseHouse baseHouse = GwjConvertUtil.convert(gwjDepositBusinessHouse, GwjBaseHouse.class);
                            baseHouse.setCurrentMoney(baseHouse.getDepositMoney());
                            if (0 == houseService.insertGwjBaseHouse(baseHouse)) {
                                throw new ServiceException("资金分户初始化保存公用户房屋失败");
                            }
                        }
                    } else {
                        GwjBaseHouse baseHouse = houseService.selectGwjBaseHouseByGwjBaseHouseId(gwjDepositBusinessHouse.getHouseId());
                        if (StringUtils.isNotNull(baseHouse)) {
                            BigDecimal depositMoney = gwjDepositBusinessHouse.getDepositMoney().add(gwjDepositBusinessHouse.getLackMoney());
                            baseHouse.setDepositMoney(StringUtils.isNull(baseHouse.getDepositMoney()) ? BigDecimal.ZERO : baseHouse.getDepositMoney().add(gwjDepositBusinessHouse.getDepositMoney()));
                            baseHouse.setCurrentMoney(StringUtils.isNull(baseHouse.getCurrentMoney()) ? BigDecimal.ZERO : baseHouse.getCurrentMoney().add(gwjDepositBusinessHouse.getDepositMoney()));
                            // 未使用之前，每笔缴存需冻结金额
                            // if (StringUtils.isNull(baseHouse.getUsedMoney()) ||
                            // baseHouse.getUsedMoney().equals(BigDecimal.ZERO)) {
                            if (StringUtils.isNull(baseHouse.getUsedMoney()) || baseHouse.getUsedMoney().compareTo(BigDecimal.ZERO) == 0) {// 20230726
                                String configValue = Convert.toStr(redisService.getCacheObject(GwjCacheConstants.GWJ_CONFIG_KEY + GwjCacheConstants.BLOCKED_MONEY_KEY));
                                baseHouse.setBlockedMoney(depositMoney.multiply(new BigDecimal(configValue)));
                            }
                            if (0 == houseService.updateGwjBaseHouse(baseHouse)) {
                                throw new ServiceException("资金分户初始化更新基础房屋信息失败");
                            }
                        }
                    }
                });
            }
            // 业务更新为完结
            business.setStatus(GwjBusinessStatus.FINISH.getCode());
            gwjDepositBusinessLogService.addFinishLog(business);
        }
        // 最终更新业务状态
        if (1 != gwjDepositBusinessService.updateGwjDepositBusiness(business)) {
            throw new ServiceException("资金分户初始化更新业务失败");
        }
    }

    /**
     * 金额维护-取消选择
     *
     * @param moneyIds 金额ID
     * @param bizId    业务ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void moneyMaintainCancelSelect(Long[] moneyIds, Long bizId) {
        // 判断是否与权限更改
        GwjDepositBusiness gwjDepositBusiness = gwjDepositBusinessService.checkPermission(bizId);
        // 查询维修资金分户（初始化）的业务金额
        GwjDepositBusinessMoney gwjDepositBusinessMoney = gwjDepositBusinessMoneyService.selectGwjDepositBusinessMoneyByBizId(bizId);
        if (StringUtils.isNull(gwjDepositBusinessMoney)) {
            throw new ServiceException("查无业务金额信息");
        }
        // 查询维修资金分户（初始化）的业务金额明细
        List<GwjDepositBusinessDetail> gwjDepositBusinessDetails = gwjDepositBusinessDetailService.selectGwjDepositBusinessDetailByBizId(bizId);
        // 获取已经绑定的金额ID
        if (StringUtils.isEmpty(gwjDepositBusinessDetails)) {
            throw new ServiceException("查无业务金额，无法取消");
        }
        // 清除分户数据的选择及业务信息
        for (Long moneyId : moneyIds) {
            R<GwjFinanceMoney> gwjFinanceMoneyR = remoteGwjFinanceService.selectFinanceMoneyByMoneyId(moneyId, SecurityConstants.INNER);
            if (!CheckRemoteServiceResultUtils.isSuccessWithData(gwjFinanceMoneyR)) {
                throw new ServiceException("分户数据查询失败");
            }
            GwjFinanceMoney gwjFinanceMoney = gwjFinanceMoneyR.getData();
            gwjFinanceMoney.setBizNum(null);
            gwjFinanceMoney.setBizId(null);
            gwjFinanceMoney.setSelectFlag(GwjBusinessHouseStatus.CANCEL.getCode());
            if (CheckRemoteServiceResultUtils.isCodeFail(remoteGwjFinanceService.clearFinanceMoneyBizInfo(gwjFinanceMoney, SecurityConstants.INNER))) {
                throw new ServiceException("分户数据更新失败");
            }
            // 减掉被取消掉的数据
            gwjDepositBusinessMoney.setTotalMoney(gwjDepositBusinessMoney.getTotalMoney().subtract(gwjFinanceMoney.getDepositMoney()));
            gwjDepositBusinessMoney.setTotalSize(gwjDepositBusinessMoney.getTotalSize().subtract(gwjFinanceMoney.getTotalSize()));
            // 删除金额明细
            if (0 == gwjDepositBusinessDetailService.deleteGwjDepositBusinessDetailByMoneyId(moneyId)) {
                throw new ServiceException("资金分户初始化重置业务金额明细失败");
            }
        }
        // 更新维修资金分户（初始化）的业务金额
        if (1 != gwjDepositBusinessMoneyService.updateGwjDepositBusinessMoney(gwjDepositBusinessMoney)) {
            throw new ServiceException("资金分户初始化更新业务金额失败");
        }
        // 更新业务差额
        gwjDepositBusiness.setLackMoney(gwjDepositBusinessMoney.getTotalMoney().subtract(gwjDepositBusinessMoney.getFactMoney()));
        if (1 != gwjDepositBusinessService.updateGwjDepositBusiness(gwjDepositBusiness)) {
            throw new ServiceException("资金分户初始化更新业务失败");
        }
    }

    /**
     * 金额维护-加入选择
     *
     * @param moneyIds 业务房屋ID
     * @param bizId    业务ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void moneyMaintainConfirmSelect(Long[] moneyIds, Long bizId) {
        // 判断是否与权限更改
        GwjDepositBusiness gwjDepositBusiness = gwjDepositBusinessService.checkPermission(bizId);
        // 查询维修资金分户（初始化）的业务金额
        GwjDepositBusinessMoney gwjDepositBusinessMoney = gwjDepositBusinessMoneyService.selectGwjDepositBusinessMoneyByBizId(bizId);
        // 绑定分户数据的选择及业务信息
        for (Long moneyId : moneyIds) {
            R<GwjFinanceMoney> gwjFinanceMoneyR = remoteGwjFinanceService.selectFinanceMoneyByMoneyId(moneyId, SecurityConstants.INNER);
            if (!CheckRemoteServiceResultUtils.isSuccessWithData(gwjFinanceMoneyR)) {
                throw new ServiceException("金额信息查询失败");
            }
            GwjFinanceMoney gwjFinanceMoney = gwjFinanceMoneyR.getData();
            gwjFinanceMoney.setBizNum(gwjDepositBusiness.getBizNum());
            gwjFinanceMoney.setBizId(gwjDepositBusiness.getBizId());
            gwjFinanceMoney.setSelectFlag(GwjBusinessHouseStatus.CONFIRM.getCode());
            if (CheckRemoteServiceResultUtils.isCodeFail(remoteGwjFinanceService.updateFinanceMoney(gwjFinanceMoney, SecurityConstants.INNER))) {
                throw new ServiceException("金额信息更新失败");
            }
            // 新曾选择的数据
            gwjDepositBusinessMoney.setTotalMoney(gwjDepositBusinessMoney.getTotalMoney().add(gwjFinanceMoney.getDepositMoney()));
            gwjDepositBusinessMoney.setTotalSize(gwjDepositBusinessMoney.getTotalSize().add(gwjFinanceMoney.getTotalSize()));
            // 插入金额明细表
            GwjDepositBusinessDetail gwjDepositBusinessDetail = new GwjDepositBusinessDetail() {
                {
                    setBizId(gwjDepositBusiness.getBizId());
                    setBizNum(gwjDepositBusiness.getBizNum());
                    setBankId(gwjFinanceMoney.getBankId());
                    setBankName(gwjFinanceMoney.getBankName());
                    setDepositMoney(gwjFinanceMoney.getDepositMoney());
                    setDepositTime(gwjFinanceMoney.getDepositTime());
                    setDepositSize(gwjFinanceMoney.getTotalSize());
                    setMoneyId(gwjFinanceMoney.getMoneyId());
                    setProjectName(gwjFinanceMoney.getProjectName());
                    setCompanyName(gwjFinanceMoney.getCompanyName());
                    setCreateBy(SecurityUtils.getLoginUser().getSysUser().getRealName());
                    setCreateTime(DateUtils.getNowDate());
                }
            };
            if (1 != gwjDepositBusinessDetailService.insertGwjDepositBusinessDetail(gwjDepositBusinessDetail)) {
                throw new ServiceException("资金分户初始化保存业务金额明细失败");
            }
        }
        // 更新维修资金分户（初始化）的业务金额
        gwjDepositBusinessMoney.setLedgerType(GwjConstants.INCOME);
        if (1 != gwjDepositBusinessMoneyService.updateGwjDepositBusinessMoney(gwjDepositBusinessMoney)) {
            throw new ServiceException("资金分户初始化更新业务金额失败");
        }
        // 更新业务差额
        gwjDepositBusiness.setLackMoney(gwjDepositBusinessMoney.getTotalMoney().subtract(gwjDepositBusinessMoney.getFactMoney()));
        if (1 != gwjDepositBusinessService.updateGwjDepositBusiness(gwjDepositBusiness)) {
            throw new ServiceException("资金分户初始化更新业务失败");
        }
    }

    /**
     * 删页
     *
     * @param bizId 业务id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBusinessData(Long bizId) {
        // 验证是否有操作权限
        GwjDepositBusiness business = gwjDepositBusinessService.checkPermission(bizId);
        // 判断当期步骤是否能删页
        if (checkStepConfigInfo(business.getStepId(), StepConfigInfoEnum.DELETE_PAGE.getCode())) {
            throw new ServiceException("当前业务步骤不允许删页");
        }
        // 清空业务信息
        business.setApplicantName("");
        business.setPhone("");
        business.setBizName("");
        business.setArchivesNum("");
        business.setLackMoney(BigDecimal.ZERO);
        business.setCommentFlag(GwjConstants.NO);
        business.setStatus(GwjBusinessStatus.NORMAL.getCode());
        business.setApplicantTime(DateUtils.getNowDate());
        gwjDepositBusinessService.updateGwjDepositBusiness(business);
        // 删除业务小区、房屋、楼栋、业主
        gwjDepositBusinessService.deleteCommunityBuildHouseOwnerData(bizId);
        // 查询业务金额明细
        List<GwjDepositBusinessDetail> gwjDepositBusinessDetails = gwjDepositBusinessDetailService.selectGwjDepositBusinessDetailByBizId(bizId);
        if (StringUtils.isNotEmpty(gwjDepositBusinessDetails)) {
            // 删除金额明细
            gwjDepositBusinessDetailService.deleteBatchGwjDepositBusinessDetailByBizId(bizId);
            // 还原已选择的金额数据
            gwjDepositBusinessDetails.forEach(detail -> {
                R<GwjFinanceMoney> gwjFinanceMoneyR = remoteGwjFinanceService.selectFinanceMoneyByMoneyId(detail.getMoneyId(), SecurityConstants.INNER);
                if (!CheckRemoteServiceResultUtils.isSuccessWithData(gwjFinanceMoneyR)) {
                    throw new ServiceException("金额信息查询失败");
                }
                GwjFinanceMoney gwjFinanceMoney = gwjFinanceMoneyR.getData();
                gwjFinanceMoney.setBizNum(null);
                gwjFinanceMoney.setBizId(null);
                gwjFinanceMoney.setSelectFlag(GwjBusinessHouseStatus.CANCEL.getCode());
                if (CheckRemoteServiceResultUtils.isCodeFail(remoteGwjFinanceService.clearFinanceMoneyBizInfo(gwjFinanceMoney, SecurityConstants.INNER))) {
                    throw new ServiceException("金额信息更新失败");
                }
            });
        }
        // 清空业务金额
        GwjDepositBusinessMoney gwjDepositBusinessMoney = gwjDepositBusinessMoneyService.selectGwjDepositBusinessMoneyByBizId(bizId);
        gwjDepositBusinessMoney.setTotalMoney(BigDecimal.ZERO);
        gwjDepositBusinessMoney.setTotalSize(BigDecimal.ZERO);
        gwjDepositBusinessMoney.setFactMoney(BigDecimal.ZERO);
        gwjDepositBusinessMoney.setFactSize(BigDecimal.ZERO);
        gwjDepositBusinessMoney.setTotalOwner(0L);
        if (1 != gwjDepositBusinessMoneyService.updateGwjDepositBusinessMoney(gwjDepositBusinessMoney)) {
            throw new ServiceException("业务金额信息更新失败");
        }
        // 删除总账流水
        if (CheckRemoteServiceResultUtils.isSuccessWithData(remoteGwjFinanceService.selectGwjFinanceAccountMainByBizId(bizId, SecurityConstants.INNER))) {
            if (CheckRemoteServiceResultUtils.isCodeFail(remoteGwjFinanceService.deleteGwjFinanceAccountMainByBizId(bizId, SecurityConstants.INNER))) {
                throw new ServiceException("删除总账流水失败");
            }
        }
        // 删除分类账流水
        if (CheckRemoteServiceResultUtils.isSuccessWithData(remoteGwjFinanceService.selectGwjFinanceAccountDetailListByBizId(bizId, SecurityConstants.INNER))) {
            if (CheckRemoteServiceResultUtils.isCodeFail(remoteGwjFinanceService.deleteGwjFinanceAccountDetailByBizId(bizId, SecurityConstants.INNER))) {
                throw new ServiceException("删除总账流水失败");
            }
        }
        // 清空日志
        gwjDepositBusinessLogService.deleteGwjDepositBusinessLogByBizId(bizId);
    }

    /**
     * 导入小区（删除原有小区、房屋、楼栋、业主、插入新小区信息）
     *
     * @param gwjDepositBusinessCommunity 要导入的小区
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importCommunity(GwjDepositBusinessCommunity gwjDepositBusinessCommunity) {
        // 验证是否有操作权限
        gwjDepositBusinessService.checkPermission(gwjDepositBusinessCommunity.getBizId());
        // 删除业务小区、房屋、楼栋、业主
        gwjDepositBusinessService.deleteCommunityBuildHouseOwnerData(gwjDepositBusinessCommunity.getBizId());
        // 业务金额数据
        GwjDepositBusinessMoney gwjDepositBusinessMoney = gwjDepositBusinessMoneyService.selectGwjDepositBusinessMoneyByBizId(gwjDepositBusinessCommunity.getBizId());
        // 涉及总户数和实际总面积和实际金额
        gwjDepositBusinessMoney.setTotalOwner(0L);
        gwjDepositBusinessMoney.setFactMoney(BigDecimal.ZERO);
        gwjDepositBusinessMoney.setFactSize(BigDecimal.ZERO);
        gwjDepositBusinessMoneyService.updateGwjDepositBusinessMoney(gwjDepositBusinessMoney);
        // 插入新小区
        gwjDepositBusinessCommunityService.insertGwjDepositBusinessCommunity(gwjDepositBusinessCommunity);
    }

    /**
     * 导入楼栋
     *
     * @param bizId    业务ID
     * @param buildIds 要导入的楼栋ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importBuild(Long bizId, Long[] buildIds) {
        // 验证是否有操作权限
        gwjDepositBusinessService.checkPermission(bizId);
        // 查询小区信息
        GwjDepositBusinessCommunity community = gwjDepositBusinessCommunityService.selectGwjDepositBusinessCommunityByBizId(bizId);
        if (StringUtils.isNull(community)) {
            throw new ServiceException("未查询到业务小区");
        }
        // 插入楼栋
        List<String> buildCodes = new ArrayList<String>();
        for (Long buildId : buildIds) {
            // 判断楼栋是否已存在
            GwjBaseBuild baseBuild = buildService.selectGwjBaseBuildByBuildId(buildId);
            if (StringUtils.isNull(baseBuild)) {
                throw new ServiceException("所选楼栋不存在，请核对");
            }
            if (StringUtils.isNotNull(gwjDepositBusinessBuildService.selectGwjDepositBusinessBuildListByBizIdAndBuildCode(bizId, baseBuild.getBuildCode()))) {
                throw new ServiceException("楼栋已存在[" + baseBuild.getBuildName() + "]，请核对");
            }
            GwjDepositBusinessBuild build = GwjConvertUtil.convert(baseBuild, GwjDepositBusinessBuild.class);
            build.setBizId(community.getBizId());
            build.setAreaId(community.getAreaId());
            build.setStreetId(community.getStreetId());
            build.setBizCommunityId(community.getBizCommunityId());
            build.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getRealName());
            build.setCreateTime(DateUtils.getNowDate());
            // 保存业务楼栋信息
            if (1 != gwjDepositBusinessBuildService.insertGwjDepositBusinessBuild(build)) {
                throw new ServiceException("资金分户初始化导入楼栋失败");
            }
            buildCodes.add(build.getBuildCode());
        }
        // 查询基础房屋数据
        List<GwjBaseHouse> houses = houseService.selectGwjBaseListByBuildCodesAndAreaId(buildCodes.toArray(new String[0]), community.getAreaId());
        // 基础房屋数据不为空
        BigDecimal totalSize = BigDecimal.ZERO;
        if (StringUtils.isNotEmpty(houses)) {
            List<GwjDepositBusinessHouse> businessHouses = GwjConvertUtil.convertList(houses, GwjDepositBusinessHouse.class);
            // 保存业务房屋数据
            for (GwjDepositBusinessHouse businessHouse : businessHouses) {
                businessHouse.setBizId(community.getBizId());
                businessHouse.setAreaId(community.getAreaId());
                businessHouse.setStreetId(community.getStreetId());
                businessHouse.setDepositSize(BigDecimal.ZERO);
                businessHouse.setDepositMoney(BigDecimal.ZERO);
                businessHouse.setLackMoney(BigDecimal.ZERO);
                businessHouse.setDepositTime(null);
                businessHouse.setSelectFlag(GwjBusinessHouseStatus.CONFIRM.getCode());
                businessHouse.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getRealName());
                businessHouse.setCreateTime(DateUtils.getNowDate());
                totalSize = totalSize.add(businessHouse.getActualSize());
            }
            if (0 == gwjDepositBusinessHouseService.insertGwjDepositBusinessHouses(businessHouses)) {
                throw new ServiceException("资金分户初始化保存业务房屋失败");
            }
            // 查询基础业主数据
            List<String> houseCodes = businessHouses.stream().map(GwjBaseBusinessHouse::getHouseCode).collect(Collectors.toList());
            // 分段查询 10个位一组
            List<List<String>> codeList = GwjConvertUtil.partition(houseCodes, 10);
            for (List<String> list : codeList) {
                // 查询基础业主数据
                List<GwjBaseOwner> owners = ownerService.selectGwjBaseListByGwjBaseHouseCodes(list.stream().toArray(String[]::new), community.getAreaId());
                // 基础业主数据不为空
                if (StringUtils.isNotEmpty(owners)) {
                    List<GwjDepositBusinessOwner> businessOwners = GwjConvertUtil.convertList(owners, GwjDepositBusinessOwner.class);
                    businessOwners.forEach(owner -> {
                        owner.setBizId(community.getBizId());
                        owner.setAreaId(community.getAreaId());
                        owner.setStreetId(community.getStreetId());
                        owner.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getRealName());
                        owner.setCreateTime(DateUtils.getNowDate());
                    });
                    if (0 == gwjDepositBusinessOwnerService.insertBatchGwjDepositBusinessOwner(businessOwners)) {
                        throw new ServiceException("资金分户初始化保存业务业主信息失败");
                    }
                }
            }
        }
        // 修改金额信息
        GwjDepositBusinessMoney money = gwjDepositBusinessMoneyService.selectGwjDepositBusinessMoneyByBizId(bizId);
        money.setFactSize(money.getFactSize().add(totalSize));
        money.setTotalOwner(money.getTotalOwner() + houses.size());
        if (1 != gwjDepositBusinessMoneyService.updateGwjDepositBusinessMoney(money)) {
            throw new ServiceException("资金分户初始化更新业务金额信息失败");
        }
    }

    /**
     * 删除业务楼栋（含房屋及业主）
     *
     * @param bizId       业务ID
     * @param bizBuildIds 业务楼栋id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBuildData(Long bizId, Long[] bizBuildIds) {
        // 验证操作权限
        GwjDepositBusiness gwjDepositBusiness = gwjDepositBusinessService.checkPermission(bizId);
        GwjDepositBusinessMoney gwjDepositBusinessMoney = gwjDepositBusinessMoneyService.selectGwjDepositBusinessMoneyByBizId(bizId);
        for (Long bizBuildId : bizBuildIds) {
            GwjDepositBusinessBuild gwjDepositBusinessBuild = gwjDepositBusinessBuildService.selectGwjDepositBusinessBuildByBizBuildId(bizBuildId);
            if (StringUtils.isNull(gwjDepositBusinessBuild)) {
                continue;
            }
            // 查询业务房屋
            List<GwjDepositBusinessHouse> gwjDepositBusinessHouses = gwjDepositBusinessHouseService.selectGwjDepositBusinessHouseListByBizIdAndBuildCode(gwjDepositBusinessBuild.getBizId(), gwjDepositBusinessBuild.getBuildCode());
            if (StringUtils.isNotEmpty(gwjDepositBusinessHouses)) {
                // 累加删除的房屋实际面积
                BigDecimal factSize = gwjDepositBusinessHouses.stream().filter(h -> StringUtils.equals(h.getSelectFlag(), GwjBusinessHouseStatus.CONFIRM.getCode())).map(GwjDepositBusinessHouse::getActualSize).reduce(BigDecimal.ZERO, BigDecimal::add);
                // 累加删除的房屋缴款金额
                BigDecimal factMoney = gwjDepositBusinessHouses.stream().filter(h -> StringUtils.equals(h.getSelectFlag(), GwjBusinessHouseStatus.CONFIRM.getCode())).map(GwjDepositBusinessHouse::getDepositMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
                // 累加删除的房屋补差金额
                BigDecimal lackMoney = gwjDepositBusinessHouses.stream().filter(h -> StringUtils.equals(h.getSelectFlag(), GwjBusinessHouseStatus.CONFIRM.getCode())).map(GwjDepositBusinessHouse::getLackMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
                // 累加删除的房屋业主
                List<GwjDepositBusinessHouse> houses = gwjDepositBusinessHouses.stream().filter(h -> StringUtils.equals(h.getSelectFlag(), GwjBusinessHouseStatus.CONFIRM.getCode())).collect(Collectors.toList());
                // 修改业务金额
                gwjDepositBusinessMoney.setFactSize(gwjDepositBusinessMoney.getFactSize().subtract(factSize));
                gwjDepositBusinessMoney.setFactMoney(gwjDepositBusinessMoney.getFactMoney().subtract(factMoney).subtract(lackMoney));
                gwjDepositBusinessMoney.setTotalOwner(gwjDepositBusinessMoney.getTotalOwner() - houses.size());
                // 修改业务差额
                gwjDepositBusiness.setLackMoney(gwjDepositBusiness.getLackMoney().add(factMoney).add(lackMoney));
                // 删除业务业主
                String[] houseCodes = gwjDepositBusinessHouses.stream().map(GwjBaseBusinessHouse::getHouseCode).toArray(String[]::new);
                gwjDepositBusinessOwnerService.deleteGwjDepositBusinessOwnerByBizIdAndHouseCodes(bizId, houseCodes);
            }
            // 删除楼栋
            gwjDepositBusinessBuildService.deleteGwjDepositBusinessBuildByBizBuildId(gwjDepositBusinessBuild.getBizBuildId());
            // 删除业务房屋
            gwjDepositBusinessHouseService.deleteGwjDepositBusinessHouseByBizIdAndBuildCode(bizId, gwjDepositBusinessBuild.getBuildCode());
        }
        // 修改业务金额
        if (1 != gwjDepositBusinessMoneyService.updateGwjDepositBusinessMoney(gwjDepositBusinessMoney)) {
            throw new ServiceException("资金分户初始化更新业务金额信息失败");
        }
        // 修改业务
        if (1 != gwjDepositBusinessService.updateGwjDepositBusiness(gwjDepositBusiness)) {
            throw new ServiceException("资金分户初始化更新业务信息失败");
        }
    }

    /**
     * 房屋维护-取消选择
     *
     * @param bizHouseIds 业务房屋ID
     * @param bizId       业务ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void houseMaintainCancelSelect(Long[] bizHouseIds, Long bizId) {
        // 验证操作权限
        GwjDepositBusiness gwjDepositBusiness = gwjDepositBusinessService.checkPermission(bizId);
        int ownerCount = 0;
        BigDecimal totalSize = BigDecimal.ZERO;
        BigDecimal totalMoney = BigDecimal.ZERO;
        BigDecimal totalLackMoney = BigDecimal.ZERO;
        for (Long bizHouseId : bizHouseIds) {
            GwjDepositBusinessHouse gwjDepositBusinessHouse = gwjDepositBusinessHouseService.selectGwjDepositBusinessHouseByBizHouseId(bizHouseId);
            if (StringUtils.isNotNull(gwjDepositBusinessHouse)) {
                ownerCount += 1;
                totalSize = totalSize.add(gwjDepositBusinessHouse.getActualSize());
                totalMoney = totalMoney.add(gwjDepositBusinessHouse.getDepositMoney());
                totalLackMoney = totalLackMoney.add(gwjDepositBusinessHouse.getLackMoney());
                // 修改选择状态
                gwjDepositBusinessHouse.setSelectFlag(GwjBusinessHouseStatus.CANCEL.getCode());
                gwjDepositBusinessHouse.setCalculateVal(BigDecimal.ZERO);
                gwjDepositBusinessHouse.setDepositSize(BigDecimal.ZERO);
                gwjDepositBusinessHouse.setDepositMoney(BigDecimal.ZERO);
                gwjDepositBusinessHouse.setLackMoney(BigDecimal.ZERO);
                gwjDepositBusinessHouse.setRemark(" ");
                gwjDepositBusinessHouse.setCalculateTypeId(GwjConstants.IMPORT_HOUSE_CALCULATE_ID);
                if (1 != gwjDepositBusinessHouseService.updateGwjDepositBusinessHouse(gwjDepositBusinessHouse)) {
                    throw new ServiceException("资金分户初始化更新业务房屋失败");
                }
            }
        }
        // 查询业务金额
        GwjDepositBusinessMoney gwjDepositBusinessMoney = gwjDepositBusinessMoneyService.selectGwjDepositBusinessMoneyByBizId(bizId);
        if (StringUtils.isNull(gwjDepositBusinessMoney)) {
            throw new ServiceException("查无业务金额");
        }
        gwjDepositBusinessMoney.setTotalOwner(gwjDepositBusinessMoney.getTotalOwner() - ownerCount);
        gwjDepositBusinessMoney.setFactSize(gwjDepositBusinessMoney.getFactSize().subtract(totalSize));
        gwjDepositBusinessMoney.setFactMoney(gwjDepositBusinessMoney.getFactMoney().subtract(totalMoney).subtract(totalLackMoney));
        if (1 != gwjDepositBusinessMoneyService.updateGwjDepositBusinessMoney(gwjDepositBusinessMoney)) {
            throw new ServiceException("资金分户初始化更新业务金额失败");
        }
        // 修改业务差额
        gwjDepositBusiness.setLackMoney(gwjDepositBusiness.getLackMoney().add(totalMoney).add(totalLackMoney));
        if (1 != gwjDepositBusinessService.updateGwjDepositBusiness(gwjDepositBusiness)) {
            throw new ServiceException("资金分户初始化更新业务差额失败");
        }
    }

    /**
     * 房屋维护-加入选择
     *
     * @param bizHouseIds 业务房屋ID
     * @param bizId       业务ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void houseMaintainConfirmSelect(Long[] bizHouseIds, Long bizId) {
        // 验证操作权限
        gwjDepositBusinessService.checkPermission(bizId);
        int ownerCount = 0;
        BigDecimal totalSize = BigDecimal.ZERO;
        for (Long bizHouseId : bizHouseIds) {
            GwjDepositBusinessHouse gwjDepositBusinessHouse = gwjDepositBusinessHouseService.selectGwjDepositBusinessHouseByBizHouseId(bizHouseId);
            if (StringUtils.isNotNull(gwjDepositBusinessHouse)) {
                ownerCount += 1;
                totalSize = totalSize.add(gwjDepositBusinessHouse.getActualSize());
                // 修改选择状态
                gwjDepositBusinessHouse.setSelectFlag(GwjBusinessHouseStatus.CONFIRM.getCode());
                if (1 != gwjDepositBusinessHouseService.updateGwjDepositBusinessHouse(gwjDepositBusinessHouse)) {
                    throw new ServiceException("资金分户初始化更新业务房屋失败");
                }
            }
        }
        // 查询业务金额
        GwjDepositBusinessMoney gwjDepositBusinessMoney = gwjDepositBusinessMoneyService.selectGwjDepositBusinessMoneyByBizId(bizId);
        if (StringUtils.isNull(gwjDepositBusinessMoney)) {
            throw new ServiceException("查无业务金额");
        }
        gwjDepositBusinessMoney.setTotalOwner(gwjDepositBusinessMoney.getTotalOwner() + ownerCount);
        gwjDepositBusinessMoney.setFactSize(gwjDepositBusinessMoney.getFactSize().add(totalSize));
        gwjDepositBusinessMoneyService.updateGwjDepositBusinessMoney(gwjDepositBusinessMoney);
        if (1 != gwjDepositBusinessMoneyService.updateGwjDepositBusinessMoney(gwjDepositBusinessMoney)) {
            throw new ServiceException("资金分户初始化更新业务金额失败");
        }
    }

    /**
     * 删除公用户楼栋
     *
     * @param bizBuildIds 业务楼栋ID
     * @param bizId       业务ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePublicBuild(Long[] bizBuildIds, Long bizId) {
        // 验证操作权限
        GwjDepositBusiness gwjDepositBusiness = gwjDepositBusinessService.checkPermission(bizId);
        // 查询业务金额
        GwjDepositBusinessMoney gwjDepositBusinessMoney = gwjDepositBusinessMoneyService.selectGwjDepositBusinessMoneyByBizId(bizId);
        if (StringUtils.isNull(gwjDepositBusinessMoney)) {
            throw new ServiceException("查无业务金额");
        }
        for (Long bizBuildId : bizBuildIds) {
            GwjDepositBusinessBuild gwjDepositBusinessBuild = gwjDepositBusinessBuildService.selectGwjDepositBusinessBuildByBizBuildId(bizBuildId);
            if (StringUtils.isNull(gwjDepositBusinessBuild)) {
                continue;
            }
            // 查询业务房屋
            List<GwjDepositBusinessHouse> gwjDepositBusinessHouses = gwjDepositBusinessHouseService.selectGwjDepositBusinessHouseListByBizIdAndBuildCode(gwjDepositBusinessBuild.getBizId(), gwjDepositBusinessBuild.getBuildCode());
            if (StringUtils.isNotEmpty(gwjDepositBusinessHouses)) {
                // 累加删除的房屋缴款金额
                BigDecimal factMoney = gwjDepositBusinessHouses.stream().filter(h -> StringUtils.equals(h.getSelectFlag(), GwjBusinessHouseStatus.CONFIRM.getCode())).map(GwjDepositBusinessHouse::getDepositMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
                // 修改业务金额
                gwjDepositBusinessMoney.setFactMoney(gwjDepositBusinessMoney.getFactMoney().subtract(factMoney));
                // 修改业务差额
                gwjDepositBusiness.setLackMoney(gwjDepositBusiness.getLackMoney().add(factMoney));
            }
            // 删除楼栋
            gwjDepositBusinessBuildService.deleteGwjDepositBusinessBuildByBizBuildId(gwjDepositBusinessBuild.getBizBuildId());
            // 删除业务房屋
            gwjDepositBusinessHouseService.deleteGwjDepositBusinessHouseByBizIdAndBuildCode(bizId, gwjDepositBusinessBuild.getBuildCode());
        }
        // 修改业务金额
        if (1 != gwjDepositBusinessMoneyService.updateGwjDepositBusinessMoney(gwjDepositBusinessMoney)) {
            throw new ServiceException("资金分户初始化更新业务金额失败");
        }
        // 修改业务差额
        if (1 != gwjDepositBusinessService.updateGwjDepositBusiness(gwjDepositBusiness)) {
            throw new ServiceException("资金分户初始化更新业务差额失败");
        }
    }

    /**
     * 删除公用户房屋
     *
     * @param bizHouseIds 业务房屋ID
     * @param bizId       业务ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePublicHouse(Long[] bizHouseIds, Long bizId) {
        // 验证操作权限
        GwjDepositBusiness gwjDepositBusiness = gwjDepositBusinessService.checkPermission(bizId);
        // 查询业务金额
        GwjDepositBusinessMoney gwjDepositBusinessMoney = gwjDepositBusinessMoneyService.selectGwjDepositBusinessMoneyByBizId(bizId);
        if (StringUtils.isNull(gwjDepositBusinessMoney)) {
            throw new ServiceException("查无业务金额");
        }
        // 查询房屋
        for (Long bizHouseId : bizHouseIds) {
            GwjDepositBusinessHouse gwjDepositBusinessHouse = gwjDepositBusinessHouseService.selectGwjDepositBusinessHouseByBizHouseId(bizHouseId);
            if (StringUtils.isNotNull(gwjDepositBusinessHouse)) {
                if (StringUtils.equals(gwjDepositBusinessHouse.getPublicFlag(), GwjConstants.NO)) {
                    throw new ServiceException("对不起，不能删除非公用户");
                }
                // 实际总金额
                gwjDepositBusinessMoney.setFactMoney(gwjDepositBusinessMoney.getFactMoney().subtract(gwjDepositBusinessHouse.getDepositMoney()));
                // 修改业务差额
                gwjDepositBusiness.setLackMoney(gwjDepositBusiness.getLackMoney().add(gwjDepositBusinessHouse.getDepositMoney()));
                // 删除公用户房屋
                gwjDepositBusinessHouseService.deleteGwjDepositBusinessHouseByBizHouseId(gwjDepositBusinessHouse.getBizHouseId());
            }
        }
        // 设置总户数
        gwjDepositBusinessMoney.setTotalOwner(null != gwjDepositBusinessMoney.getTotalOwner() && !NumberUtil.equals(gwjDepositBusinessMoney.getTotalOwner(), 0L) ? gwjDepositBusinessMoney.getTotalOwner() - 1L : 0L);
        if (1 != gwjDepositBusinessMoneyService.updateGwjDepositBusinessMoney(gwjDepositBusinessMoney)) {
            throw new ServiceException("资金分户初始化更新业务金额失败");
        }
        // 修改业务差额
        if (1 != gwjDepositBusinessService.updateGwjDepositBusiness(gwjDepositBusiness)) {
            throw new ServiceException("资金分户初始化更新业务差额失败");
        }
    }

    /**
     * 创建公用户楼栋
     *
     * @param gwjPublicAccountRequest 请求参数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createPublicBuild(GwjPublicAccountRequest gwjPublicAccountRequest) {
        // 验证操作权限
        GwjDepositBusiness gwjDepositBusiness = gwjDepositBusinessService.checkPermission(gwjPublicAccountRequest.getBizId());
        // 查询业务小区
        GwjDepositBusinessCommunity gwjDepositBusinessCommunity = gwjDepositBusinessCommunityService.selectGwjDepositBusinessCommunityByBizId(gwjPublicAccountRequest.getBizId());
        if (StringUtils.isNull(gwjDepositBusinessCommunity)) {
            throw new ServiceException("查无业务小区");
        }
        // 创建公用户楼栋
        GwjDepositBusinessBuild gwjDepositBusinessBuild = new GwjDepositBusinessBuild() {
            {
                setBuildName(gwjPublicAccountRequest.getBuildName());
                setBuildNo(gwjPublicAccountRequest.getBuildName());
                setBizId(gwjPublicAccountRequest.getBizId());
                setAreaId(gwjDepositBusinessCommunity.getAreaId());
                setStreetId(gwjDepositBusinessCommunity.getStreetId());
                setBizCommunityId(gwjDepositBusinessCommunity.getBizCommunityId());
                setPublicCreateTime(DateUtils.getNowDate());
                setBuildType(GwjConstants.PUBLIC_BUILD_TYPE);
                setPublicFlag(GwjConstants.YES);
                setBuildCode(GwjCustomImportConstants.PUBLIC_HOUSE + gwjImpSqeService.reserveSqeByIndex("build", 1L));
                setTotalLayer(0);
            }
        };
        if (1 != gwjDepositBusinessBuildService.insertGwjDepositBusinessBuild(gwjDepositBusinessBuild)) {
            throw new ServiceException("资金分户初始化保存公用户楼栋失败");
        }
        // 创建公用户房屋
        GwjDepositBusinessHouse gwjDepositBusinessHouse = new GwjDepositBusinessHouse() {
            {
                setBizId(gwjPublicAccountRequest.getBizId());
                setDepositMoney(gwjPublicAccountRequest.getPublicMoney());
                setRoomNum(gwjPublicAccountRequest.getRoomNum());
                setAreaId(gwjDepositBusinessCommunity.getAreaId());
                setStreetId(gwjDepositBusinessCommunity.getStreetId());
                setActualSize(BigDecimal.ZERO);
                setForecastSize(BigDecimal.ZERO);
                setBuildCode(gwjDepositBusinessBuild.getBuildCode());
                setSelectFlag(GwjBusinessHouseStatus.CONFIRM.getCode());
                setHouseCode(GwjCustomImportConstants.PUBLIC_HOUSE + gwjImpSqeService.reserveSqeByIndex("house", 1L));
                setNominalLayer("0");
                setUseType("公用户");
                setHouseLocation(gwjDepositBusinessCommunity.getCommunityName() + gwjDepositBusinessBuild.getBuildName() + "(" + gwjPublicAccountRequest.getRoomNum() + ")");
                setPublicCreateTime(DateUtils.getNowDate());
                setPublicFlag(GwjConstants.YES);
            }
        };
        if (1 != gwjDepositBusinessHouseService.insertGwjDepositBusinessHouse(gwjDepositBusinessHouse)) {
            throw new ServiceException("资金分户初始化保存公用户房屋失败");
        }
        // 查询业务金额
        GwjDepositBusinessMoney gwjDepositBusinessMoney = gwjDepositBusinessMoneyService.selectGwjDepositBusinessMoneyByBizId(gwjPublicAccountRequest.getBizId());
        if (StringUtils.isNull(gwjDepositBusinessMoney)) {
            throw new ServiceException("查无业务金额");
        }
        // 实际总金额
        gwjDepositBusinessMoney.setFactMoney(gwjDepositBusinessMoney.getFactMoney().add(gwjDepositBusinessHouse.getDepositMoney()));
        if (1 != gwjDepositBusinessMoneyService.updateGwjDepositBusinessMoney(gwjDepositBusinessMoney)) {
            throw new ServiceException("资金分户初始化更新业务金额失败");
        }
        // 修改业务差额
        gwjDepositBusiness.setLackMoney(gwjDepositBusiness.getLackMoney().subtract(gwjPublicAccountRequest.getPublicMoney()));
        if (1 != gwjDepositBusinessService.updateGwjDepositBusiness(gwjDepositBusiness)) {
            throw new ServiceException("资金分户初始化更新业务差额失败");
        }
    }

    /**
     * 创建公用户房屋
     *
     * @param gwjPublicAccountRequest 请求参数
     */
    @Override
    public void createPublicHouse(GwjPublicAccountRequest gwjPublicAccountRequest) {
        // 验证是否有操作权限
        Long bizId = gwjPublicAccountRequest.getBizId();
        GwjDepositBusiness gwjDepositBusiness = gwjDepositBusinessService.checkPermission(bizId);
        // 查询业务小区
        GwjDepositBusinessCommunity gwjDepositBusinessCommunity = gwjDepositBusinessCommunityService.selectGwjDepositBusinessCommunityByBizId(gwjPublicAccountRequest.getBizId());
        if (StringUtils.isNull(gwjDepositBusinessCommunity)) {
            throw new ServiceException("查无业务小区");
        }
        // 查询业务楼栋
        GwjDepositBusinessBuild gwjDepositBusinessBuild = gwjDepositBusinessBuildService.selectGwjDepositBusinessBuildByBizBuildId(gwjPublicAccountRequest.getBizBuildId());
        if (StringUtils.isNull(gwjDepositBusinessBuild)) {
            throw new ServiceException("查无业务楼栋");
        }
        // 创建公用户房屋
        GwjDepositBusinessHouse gwjDepositBusinessHouse = new GwjDepositBusinessHouse() {
            {
                setBizId(bizId);
                setBuildCode(gwjDepositBusinessBuild.getBuildCode());
                setAreaId(gwjDepositBusinessCommunity.getAreaId());
                setStreetId(gwjDepositBusinessCommunity.getStreetId());
                setDepositMoney(gwjPublicAccountRequest.getPublicMoney());
                setRoomNum(gwjPublicAccountRequest.getRoomNum());
                setHouseCode(GwjCustomImportConstants.PUBLIC_HOUSE + gwjImpSqeService.reserveSqeByIndex("house", 1L));
                setSelectFlag(GwjBusinessHouseStatus.CONFIRM.getCode());
                setNominalLayer("0");
                setUseType("公用户");
                setForecastSize(BigDecimal.ZERO);
                setActualSize(BigDecimal.ZERO);
                setHouseLocation(gwjDepositBusinessCommunity.getCommunityName() + gwjDepositBusinessBuild.getBuildName() + "(" + gwjPublicAccountRequest.getRoomNum() + ")");
                setPublicCreateTime(DateUtils.getNowDate());
                setPublicFlag(GwjConstants.YES);
            }
        };
        if (1 != gwjDepositBusinessHouseService.insertGwjDepositBusinessHouse(gwjDepositBusinessHouse)) {
            throw new ServiceException("资金分户初始化保存公用户房屋失败");
        }
        // 查询业务金额
        GwjDepositBusinessMoney gwjDepositBusinessMoney = gwjDepositBusinessMoneyService.selectGwjDepositBusinessMoneyByBizId(bizId);
        if (StringUtils.isNull(gwjDepositBusinessMoney)) {
            throw new ServiceException("查无业务金额");
        }
        // 实际总金额
        gwjDepositBusinessMoney.setFactMoney(gwjDepositBusinessMoney.getFactMoney().add(gwjPublicAccountRequest.getPublicMoney()));
        gwjDepositBusinessMoney.setTotalOwner(null != gwjDepositBusinessMoney.getTotalOwner() ? gwjDepositBusinessMoney.getTotalOwner() + 1L : 1L);
        if (1 != gwjDepositBusinessMoneyService.updateGwjDepositBusinessMoney(gwjDepositBusinessMoney)) {
            throw new ServiceException("资金分户初始化更新业务金额失败");
        }
        // 修改业务差额
        gwjDepositBusiness.setLackMoney(gwjDepositBusiness.getLackMoney().subtract(gwjPublicAccountRequest.getPublicMoney()));
        if (1 != gwjDepositBusinessService.updateGwjDepositBusiness(gwjDepositBusiness)) {
            throw new ServiceException("资金分户初始化更新业务差额失败");
        }
    }

    /**
     * 编辑公用户房屋
     *
     * @param gwjPublicBusinessHouseRequests 房屋数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePublicHouse(List<GwjPublicBusinessHouseRequest> gwjPublicBusinessHouseRequests) {
        if (StringUtils.isEmpty(gwjPublicBusinessHouseRequests)) {
            throw new ServiceException("公用户房屋数据为空");
        }
        if (StringUtils.isNull(gwjPublicBusinessHouseRequests.get(0).getBizId())) {
            throw new ServiceException("查无业务信息");
        }
        Long bizId = gwjPublicBusinessHouseRequests.get(0).getBizId();
        // 验证是否有操作权限
        GwjDepositBusiness gwjDepositBusiness = gwjDepositBusinessService.checkPermission(bizId);
        List<GwjDepositBusinessHouse> gwjDepositBusinessHouses = GwjConvertUtil.convertList(gwjPublicBusinessHouseRequests, GwjDepositBusinessHouse.class);
        // 金额数据计算
        BigDecimal oldMoney = BigDecimal.ZERO;
        BigDecimal money = BigDecimal.ZERO;
        for (GwjDepositBusinessHouse h : gwjDepositBusinessHouses) {
            // 查询原来的数据
            GwjDepositBusinessHouse house = gwjDepositBusinessHouseService.selectGwjDepositBusinessHouseByBizHouseId(h.getBizHouseId());
            if (StringUtils.isNotNull(house)) {
                if (!NumberUtil.equals(house.getDepositMoney(), h.getDepositMoney())) {
                    money = money.add(h.getDepositMoney());
                    oldMoney = oldMoney.add(house.getDepositMoney());
                }
                if (1 != gwjDepositBusinessHouseService.updateGwjDepositBusinessHouse(h)) {
                    throw new ServiceException("资金分户初始化更新业务房屋失败");
                }
            }
        }
        // 修改业务金额
        GwjDepositBusinessMoney gwjDepositBusinessMoney = gwjDepositBusinessMoneyService.selectGwjDepositBusinessMoneyByBizId(bizId);
        if (StringUtils.isNull(gwjDepositBusinessMoney)) {
            throw new ServiceException("查无业务金额");
        }
        gwjDepositBusinessMoney.setFactMoney(gwjDepositBusinessMoney.getFactMoney().subtract(oldMoney).add(money));
        if (1 != gwjDepositBusinessMoneyService.updateGwjDepositBusinessMoney(gwjDepositBusinessMoney)) {
            throw new ServiceException("资金分户初始化更新业务金额失败");
        }
        // 修改业务差额
        gwjDepositBusiness.setLackMoney(gwjDepositBusiness.getLackMoney().add(oldMoney).subtract(money));
        if (1 != gwjDepositBusinessService.updateGwjDepositBusiness(gwjDepositBusiness)) {
            throw new ServiceException("资金分户初始化更新业务差额失败");
        }
    }

    /**
     * 修改房屋的缴款面积
     *
     * @param gwjDepositBusinessHouse 业务房屋
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateGwjDepositBusinessHouseDepositSize(GwjDepositBusinessHouse gwjDepositBusinessHouse) {
        // 验证是否有操作权限
        GwjDepositBusiness gwjDepositBusiness = gwjDepositBusinessService.checkPermission(gwjDepositBusinessHouse.getBizId());
        GwjDepositBusinessHouse oldGwjDepositBusinessHouse = gwjDepositBusinessHouseService.selectGwjDepositBusinessHouseByBizHouseId(gwjDepositBusinessHouse.getBizHouseId());
        if (StringUtils.isNull(oldGwjDepositBusinessHouse)) {
            throw new ServiceException("查无房屋数据");
        }
        oldGwjDepositBusinessHouse.setRemark(StringUtils.isNotBlank(oldGwjDepositBusinessHouse.getRemark()) ? oldGwjDepositBusinessHouse.getRemark() + ";" : "");
        // 新增备注
        gwjDepositBusinessHouse.setRemark(oldGwjDepositBusinessHouse.getRemark() + DateUtils.getTime() + GwjRemarkConstants.UPDATE_PAID_SIZE.replace("{oldDepositSize}", oldGwjDepositBusinessHouse.getDepositSize().toString()).replace("{depositSize}", gwjDepositBusinessHouse.getDepositSize().toString()));
        // 修改业务为有批注
        if (StringUtils.equals(gwjDepositBusiness.getCommentFlag(), GwjConstants.NO)) {
            gwjDepositBusiness.setCommentFlag(GwjConstants.YES);
            gwjDepositBusinessService.updateGwjDepositBusiness(gwjDepositBusiness);
        }
        if (1 != gwjDepositBusinessHouseService.updateGwjDepositBusinessHouse(gwjDepositBusinessHouse)) {
            throw new ServiceException("资金分户初始化修改房屋缴款面积失败");
        }
        return Boolean.TRUE;
    }

    /**
     * 修改房屋的补差
     *
     * @param gwjDepositBusinessHouse 业务房屋
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateGwjDepositBusinessHouseLackMoney(GwjDepositBusinessHouse gwjDepositBusinessHouse) {
        // 验证是否有操作权限
        GwjDepositBusiness gwjDepositBusiness = gwjDepositBusinessService.checkPermission(gwjDepositBusinessHouse.getBizId());
        GwjDepositBusinessHouse oldGwjDepositBusinessHouse = gwjDepositBusinessHouseService.selectGwjDepositBusinessHouseByBizHouseId(gwjDepositBusinessHouse.getBizHouseId());
        if (StringUtils.isNull(oldGwjDepositBusinessHouse)) {
            throw new ServiceException("查无房屋数据");
        }
        oldGwjDepositBusinessHouse.setRemark(StringUtils.isNotBlank(oldGwjDepositBusinessHouse.getRemark()) ? oldGwjDepositBusinessHouse.getRemark() + ";" : "");
        // 新增备注
        gwjDepositBusinessHouse.setRemark(oldGwjDepositBusinessHouse.getRemark() + DateUtils.getTime() + GwjRemarkConstants.UPDATE_LACK_MONEY.replace("{oldLackMoney}", oldGwjDepositBusinessHouse.getLackMoney().toString()).replace("{lackMoney}", gwjDepositBusinessHouse.getLackMoney().toString()));
        // 修改业务为有批注
        if (StringUtils.equals(gwjDepositBusiness.getCommentFlag(), GwjConstants.NO)) {
            gwjDepositBusiness.setCommentFlag(GwjConstants.YES);
        }
        // 修改业务差额
        gwjDepositBusiness.setLackMoney(gwjDepositBusiness.getLackMoney().add(oldGwjDepositBusinessHouse.getLackMoney()).subtract(gwjDepositBusinessHouse.getLackMoney()));
        if (1 != gwjDepositBusinessService.updateGwjDepositBusiness(gwjDepositBusiness)) {
            throw new ServiceException("资金分户初始化更新业务失败");
        }
        // 修改业务金额
        GwjDepositBusinessMoney gwjDepositBusinessMoney = gwjDepositBusinessMoneyService.selectGwjDepositBusinessMoneyByBizId(gwjDepositBusinessHouse.getBizId());
        if (StringUtils.isNull(gwjDepositBusinessMoney)) {
            throw new ServiceException("查无业务金额");
        }
        gwjDepositBusinessMoney.setFactMoney(NumberUtil.equals(oldGwjDepositBusinessHouse.getLackMoney(), BigDecimal.ZERO) ? gwjDepositBusinessMoney.getFactMoney().add(gwjDepositBusinessHouse.getLackMoney()) : gwjDepositBusinessMoney.getFactMoney().subtract(oldGwjDepositBusinessHouse.getLackMoney()).add(gwjDepositBusinessHouse.getLackMoney()));
        if (1 != gwjDepositBusinessMoneyService.updateGwjDepositBusinessMoney(gwjDepositBusinessMoney)) {
            throw new ServiceException("资金分户初始化更新业务金额失败");
        }
        if (1 != gwjDepositBusinessHouseService.updateGwjDepositBusinessHouse(gwjDepositBusinessHouse)) {
            throw new ServiceException("资金分户初始化修改房屋补差失败");
        }
        return Boolean.TRUE;
    }

    /**
     * 缴存日期存入
     *
     * @param bizId       业务ID
     * @param depositTime 缴存日期
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateGwjDepositBusinessHouseDepositTime(Long bizId, Date depositTime) {
        // 验证是否有操作权限
        gwjDepositBusinessService.checkPermission(bizId);
        // 查询已选择的房屋
        GwjDepositBusinessHouse gwjDepositBusinessHouse = new GwjDepositBusinessHouse();
        gwjDepositBusinessHouse.setBizId(bizId);
        gwjDepositBusinessHouse.setSelectFlag(GwjBusinessHouseStatus.CONFIRM.getCode());
        List<GwjDepositBusinessHouse> gwjDepositBusinessHouses = gwjDepositBusinessHouseService.selectGwjDepositBusinessHouseList(gwjDepositBusinessHouse);
        gwjDepositBusinessHouses.forEach(h -> {
            // 修改时间
            h.setDepositTime(depositTime);
        });
        gwjDepositBusinessHouseService.updateBatchGwjDepositBusinessHouse(gwjDepositBusinessHouses);
    }

    /**
     * 根据标准计算楼栋房屋
     *
     * @param gwjCalculateRequest 计算信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void calculateHouse(GwjCalculateRequest gwjCalculateRequest) {
        Long bizId = gwjCalculateRequest.getBizId();
        String[] buildCodes = gwjCalculateRequest.getBuildCodes();
        // 验证是否有操作权限
        GwjDepositBusiness gwjDepositBusiness = gwjDepositBusinessService.checkPermission(bizId);
        // 查询计算标准公式
        R<GwjConfCalculateType> gwjCommonCalculateTypeR = remoteGwjConfigService.selectGwjConfCalculateTypeByCalculateTypeId(gwjCalculateRequest.getCalculateTypeId(), SecurityConstants.INNER);
        if (!CheckRemoteServiceResultUtils.isSuccessWithData(gwjCommonCalculateTypeR)) {
            throw new ServiceException("计算标准查询失败");
        }
        GwjConfCalculateType gwjConfCalculateType = gwjCommonCalculateTypeR.getData();
        // 查询涉及总金额
        GwjDepositBusinessMoney gwjDepositBusinessMoney = gwjDepositBusinessMoneyService.selectGwjDepositBusinessMoneyByBizId(bizId);
        if (StringUtils.isNull(gwjDepositBusinessMoney)) {
            throw new ServiceException("查无业务金额");
        }
        BigDecimal totalDepositMoney = BigDecimal.ZERO;
        // 平摊
        if (StringUtils.equals("2", gwjConfCalculateType.getGetValFlag())) {
            List<GwjDepositBusinessHouse> gwjDepositBusinessHouses = gwjDepositBusinessHouseService.selectGwjDepositBusinessHouseListByBizIdAndBuildCodes(bizId, buildCodes);
            if (StringUtils.isEmpty(gwjDepositBusinessHouses)) {
                throw new ServiceException("查无房屋数据");
            }
            BigDecimal totalSize;
            if (StringUtils.equals(gwjCalculateRequest.getSizeType(), GwjConstants.ACTUAL_SIZE)) {
                totalSize = gwjDepositBusinessHouseService.countActualSizeByBizIdAndBuildCodes(bizId, buildCodes);
            } else {
                totalSize = gwjDepositBusinessHouseService.countForecastSizeByBizIdAndBuildCodes(bizId, buildCodes);
            }
            BigDecimal calculateVal = gwjDepositBusinessMoney.getTotalMoney().divide(totalSize, 2, RoundingMode.HALF_UP);
            for (GwjDepositBusinessHouse gwjDepositBusinessHouse : gwjDepositBusinessHouses) {
                if (StringUtils.isBlank(gwjDepositBusinessHouse.getSelectFlag())) {
                    throw new ServiceException("房屋数据不全[selectFlag]为空");
                }
                if (StringUtils.isBlank(gwjDepositBusinessHouse.getPublicFlag())) {
                    throw new ServiceException("房屋数据不全[publicFlag]为空");
                }
                // 排除未选择及公用户
                if (StringUtils.equals(gwjDepositBusinessHouse.getSelectFlag(), GwjBusinessHouseStatus.CANCEL.getCode()) || StringUtils.equals(gwjDepositBusinessHouse.getPublicFlag(), GwjConstants.YES)) {
                    continue;
                }
                // 计算总面积、判断期房还是现房
                if (StringUtils.equals(gwjCalculateRequest.getSizeType(), GwjConstants.ACTUAL_SIZE)) {
                    gwjDepositBusinessHouse.setDepositSize(gwjDepositBusinessHouse.getActualSize());
                } else {
                    gwjDepositBusinessHouse.setDepositSize(gwjDepositBusinessHouse.getForecastSize());
                }
                // 对象转换为map并计算
                gwjDepositBusinessHouse.setCalculateVal(calculateVal);
                Map<String, Object> temp = BeanUtil.beanToMap(gwjDepositBusinessHouse);
                temp.put("totalMoney", gwjDepositBusinessMoney.getTotalMoney());
                temp.put("totalSize", totalSize);
                gwjDepositBusinessHouse.setDepositMoney(GwjCalculateFormulaUtil.getFormulaResult(gwjConfCalculateType.getFormula(), temp));
                // 更新数据
                gwjDepositBusinessHouse.setCalculateTypeId(gwjCalculateRequest.getCalculateTypeId());
                gwjDepositBusinessHouse.setCalculateVal(BigDecimal.ZERO);
                if (1 != gwjDepositBusinessHouseService.updateGwjDepositBusinessHouse(gwjDepositBusinessHouse)) {
                    throw new ServiceException("资金分户初始化更新业务房屋失败");
                }
                // 缴存金额累计，用于计算差额
                totalDepositMoney = totalDepositMoney.add(gwjDepositBusinessHouse.getDepositMoney()).add(gwjDepositBusinessHouse.getLackMoney());
            }
        } else {
            for (String buildCode : gwjCalculateRequest.getBuildCodes()) {
                // 查询楼栋信息
                GwjDepositBusinessBuild gwjDepositBusinessBuild = gwjDepositBusinessBuildService.selectGwjDepositBusinessBuildListByBizIdAndBuildCode(bizId, buildCode);
                if (StringUtils.isNull(gwjDepositBusinessBuild)) {
                    throw new ServiceException("查无楼栋信息");
                }
                if (gwjDepositBusinessBuild.getBuildType() == 0 && !StringUtils.equals("0", gwjConfCalculateType.getGetValFlag())) {
                    throw new ServiceException("请选择楼栋类型后，再进行计算");
                }
                // 排除未选择及公用户
                List<GwjDepositBusinessHouse> gwjDepositBusinessHouses = gwjDepositBusinessHouseService.selectGwjDepositBusinessHouseListByBizIdAndBuildCode(bizId, buildCode);
                if (StringUtils.isEmpty(gwjDepositBusinessHouses)) {
                    throw new ServiceException("查无房屋数据");
                }
                for (GwjDepositBusinessHouse gwjDepositBusinessHouse : gwjDepositBusinessHouses) {
                    // 排除未选择、公用户房屋
                    if (StringUtils.isBlank(gwjDepositBusinessHouse.getSelectFlag())) {
                        throw new ServiceException("房屋数据不全[selectFlag]为空");
                    }
                    if (StringUtils.isBlank(gwjDepositBusinessHouse.getPublicFlag())) {
                        throw new ServiceException("房屋数据不全[publicFlag]为空");
                    }
                    if (StringUtils.equals(gwjDepositBusinessHouse.getSelectFlag(), GwjBusinessHouseStatus.CANCEL.getCode()) || StringUtils.equals(gwjDepositBusinessHouse.getPublicFlag(), GwjConstants.YES)) {
                        continue;
                    }
                    // 设置缴存面积
                    if (StringUtils.equals(gwjCalculateRequest.getSizeType(), GwjConstants.ACTUAL_SIZE)) {
                        gwjDepositBusinessHouse.setDepositSize(gwjDepositBusinessHouse.getActualSize());
                    } else {
                        gwjDepositBusinessHouse.setDepositSize(gwjDepositBusinessHouse.getForecastSize());
                    }
                    if (StringUtils.equals("1", gwjConfCalculateType.getGetValFlag())) {
                        // 查询计算标准值
                        R<GwjConfCalculateData> gwjConfCalculateDataR = remoteGwjConfigService.selectCalculateDataByCalculateTypeIdAndAreaIdAndBuildTypeId(gwjConfCalculateType.getCalculateTypeId(), gwjDepositBusinessBuild.getAreaId(), gwjDepositBusinessBuild.getBuildType(), SecurityConstants.INNER);
                        if (!CheckRemoteServiceResultUtils.isSuccessWithData(gwjConfCalculateDataR)) {
                            throw new ServiceException("计算标准值查询失败");
                        }
                        GwjConfCalculateData gwjConfCalculateData = gwjConfCalculateDataR.getData();
                        if (StringUtils.isNull(gwjConfCalculateData)) {
                            throw new ServiceException("查无计算标准值");
                        }
                        gwjDepositBusinessHouse.setCalculateVal(gwjConfCalculateData.getCalculateVal());
                        // 对象转换为map并计算
                        gwjDepositBusinessHouse.setDepositMoney(GwjCalculateFormulaUtil.getFormulaResult(gwjConfCalculateType.getFormula(), BeanUtil.beanToMap(gwjDepositBusinessHouse)));
                    } else if (StringUtils.equals("0", gwjConfCalculateType.getGetValFlag())) {
                        if (StringUtils.isNull(gwjCalculateRequest.getOtherCalculateVal()) || NumberUtil.equals(gwjCalculateRequest.getOtherCalculateVal(), BigDecimal.ZERO)) {
                            throw new ServiceException("请输入计算标准金额");
                        }
                        gwjDepositBusinessHouse.setCalculateVal(gwjCalculateRequest.getOtherCalculateVal());
                        // 对象转换为map并计算
                        gwjDepositBusinessHouse.setDepositMoney(GwjCalculateFormulaUtil.getFormulaResult(gwjConfCalculateType.getFormula(), BeanUtil.beanToMap(gwjDepositBusinessHouse)));
                    }
                    // 更新数据
                    gwjDepositBusinessHouse.setCalculateTypeId(gwjCalculateRequest.getCalculateTypeId());
                    if (1 != gwjDepositBusinessHouseService.updateGwjDepositBusinessHouse(gwjDepositBusinessHouse)) {
                        throw new ServiceException("资金分户初始化更新业务房屋失败");
                    }
                    // 缴存金额累计，用于计算差额
                    totalDepositMoney = totalDepositMoney.add(gwjDepositBusinessHouse.getDepositMoney()).add(gwjDepositBusinessHouse.getLackMoney());
                }
            }
        }
        // 修改业务金额 实际金额
        // 公用户金额累加
        List<GwjDepositBusinessHouse> publicHouses = gwjDepositBusinessHouseService.selectGwjDepositBusinessHouseList(new GwjDepositBusinessHouse() {
            {
                setBizId(bizId);
                setSelectFlag(GwjBusinessHouseStatus.CONFIRM.getCode());
                setPublicFlag(GwjConstants.YES);
            }
        });
        BigDecimal publicMoney = publicHouses.stream().map(GwjDepositBusinessHouse::getDepositMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        gwjDepositBusinessMoney.setFactMoney(totalDepositMoney.add(publicMoney));
        if (1 != gwjDepositBusinessMoneyService.updateGwjDepositBusinessMoney(gwjDepositBusinessMoney)) {
            throw new ServiceException("资金分户初始化更新业务金额失败");
        }
        // 修改业务差额
        gwjDepositBusiness.setLackMoney(gwjDepositBusinessMoney.getTotalMoney().subtract(gwjDepositBusinessMoney.getFactMoney()));
        if (1 != gwjDepositBusinessService.updateGwjDepositBusiness(gwjDepositBusiness)) {
            throw new ServiceException("资金分户初始化更新业务失败");
        }
    }

    /**
     * 生成财务流水
     *
     * @param bizId 业务ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void genFinancialStatement(Long bizId) {
        // 验证用户是否拥有操作权限
        GwjDepositBusiness business = gwjDepositBusinessService.checkPermission(bizId);
        // 重置总账、分账流水
        if (!gwjDepositBusinessService.removeLedger(bizId)) {
            throw new ServiceException("总账、分账流水重置失败");
        }
        // 生成总账、分账流水
        // 查询缴费信息
        GwjDepositBusinessMoney businessMoney = gwjDepositBusinessMoneyService.selectGwjDepositBusinessMoneyByBizId(bizId);
        if (ObjectUtil.isEmpty(businessMoney)) {
            throw new ServiceException("未查询到对应缴费信息");
        }
        // 查询缴费明细
        List<GwjDepositBusinessDetail> details = gwjDepositBusinessDetailService.selectGwjDepositBusinessDetailByBizId(bizId);
        if (ObjectUtil.isEmpty(details)) {
            throw new ServiceException("未查询到对应缴费明细");
        }
        // 查询房屋信息
        List<GwjDepositBusinessHouse> houseList = gwjDepositBusinessHouseService.selectGwjDepositBusinessHouseListByBizId(bizId);
        if (ObjectUtil.isEmpty(houseList)) {
            throw new ServiceException("未查询到对应房屋信息");
        }
        // 查询银行信息
        Map<Long, GwjFinanceBank> bankMap = new HashMap<Long, GwjFinanceBank>(details.size());
        details.forEach(item -> {
            GwjFinanceBank bank = remoteGwjFinanceService.selectFinanceBankByBankIdAndAreaId(item.getBankId(), business.getAreaId(), SecurityConstants.INNER).getData();
            if (ObjectUtil.isEmpty(bank)) {
                throw new ServiceException("未查询到对应银行");
            }
            bankMap.put(bank.getBankId(), bank);
        });
        // 处理总账信息
        BigDecimal zero = new BigDecimal("0.00");
        details.forEach(item -> {
            // 设置总账参数
            GwjFinanceAccountMain accountMain = new GwjFinanceAccountMain();
            Long bankId = item.getBankId();
            accountMain.setBizId(bizId);
            accountMain.setBizNum(item.getBizNum());
            accountMain.setBizFlagId(business.getBizFlagId());
            accountMain.setBankId(bankId);
            accountMain.setBankName(bankMap.get(bankId).getBankName());
            accountMain.setBankAccount(bankMap.get(bankId).getBankAccount());
            accountMain.setBankAccountType(bankMap.get(bankId).getBankAccountType());
            accountMain.setIncomeMoney(item.getDepositMoney());
            accountMain.setPayMoney(zero);
            accountMain.setDealTime(DateUtils.getNowDate());
            accountMain.setCheckType(GwjCheckAccountType.HANDWORK.getCode());
            accountMain.setCheckStatus(GwjCheckAccountStatus.NOT_CHECK.getCode());
            accountMain.setAreaId(business.getAreaId());
            accountMain.setDealId(item.getInvoiceNumber());
            // 插入总账信息
            if (1 != remoteGwjFinanceService.insertGwjFinanceAccountMain(accountMain, SecurityConstants.INNER).getData()) {
                throw new ServiceException("总账信息生成失败");
            }
        });
        // 处理分账信息
        ArrayList<GwjFinanceAccountDetail> detailArrayList = new ArrayList<GwjFinanceAccountDetail>(houseList.size());
        detailArrayList.addAll(houseList.stream().map(item -> {
            GwjFinanceAccountDetail detail = new GwjFinanceAccountDetail();
            detail.setBizId(bizId);
            detail.setBizNum(business.getBizNum());
            detail.setBizFlagId(business.getBizFlagId());
            detail.setHouseCode(item.getHouseCode());
            detail.setIncomeMoney(item.getDepositMoney().add(item.getLackMoney()));
            detail.setPayMoney(zero);
            detail.setDealTime(DateUtils.getNowDate());
            detail.setCheckType(GwjCheckAccountType.HANDWORK.getCode());
            detail.setCheckStatus(GwjCheckAccountStatus.NOT_CHECK.getCode());
            detail.setAreaId(business.getAreaId());
            return detail;
        }).collect(Collectors.toList()));
        // 批量插入分账信息
        if (1 != remoteGwjFinanceService.insertBatchGwjFinanceAccountDetailInner(detailArrayList, SecurityConstants.INNER).getData()) {
            throw new ServiceException("分账信息生成失败");
        }
    }

    /**
     * 财务对账
     *
     * @param bizId 业务ID
     */
    @Override
    public void financeCheck(Long bizId) {
        // 验证是否有操作权限
        GwjDepositBusiness business = gwjDepositBusinessService.checkPermission(bizId);
        // 检验步骤
        if (checkStepConfigInfo(business.getStepId(), StepConfigInfoEnum.FINANCE_CHECK.getCode())) {
            throw new ServiceException("当前步骤不允许操作财务对账");
        }
        // 查询业务金额
        GwjDepositBusinessMoney gwjDepositBusinessMoney = gwjDepositBusinessMoneyService.selectGwjDepositBusinessMoneyByBizId(bizId);
        if (StringUtils.isNull(gwjDepositBusinessMoney)) {
            throw new ServiceException("查无金额信息");
        }
        // 判断实际金额和涉及金额是否一致
        if (!NumberUtil.equals(gwjDepositBusinessMoney.getTotalMoney(), gwjDepositBusinessMoney.getFactMoney())) {
            throw new ServiceException("对账失败，实缴金额与应交金额不相等，请重新核对");
        }
        // 查询总账流水
        R<List<GwjFinanceAccountMain>> gwjFinanceAccountMainsR = remoteGwjFinanceService.selectGwjFinanceAccountMainList(new GwjFinanceAccountMain() {
            {
                setBizId(bizId);
            }
        }, SecurityConstants.INNER);
        if (CheckRemoteServiceResultUtils.isCodeFail(gwjFinanceAccountMainsR)) {
            throw new ServiceException("总账流水查询失败");
        }
        if (StringUtils.isEmpty(gwjFinanceAccountMainsR.getData())) {
            throw new ServiceException("对账失败，未生成流水账单");
        }
        // 判断总账和涉及金额是否一致
        BigDecimal totalMainMoney = gwjFinanceAccountMainsR.getData().stream().map(GwjFinanceAccountMain::getIncomeMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        if (!NumberUtil.equals(gwjDepositBusinessMoney.getTotalMoney(), totalMainMoney)) {
            throw new ServiceException("对账失败，实缴金额与应交金额不相等，请重新核对");
        }
        // 查询分账流水
        R<List<GwjFinanceAccountDetail>> gwjFinanceAccountDetailsR = remoteGwjFinanceService.selectGwjFinanceAccountDetailListByBizId(bizId, SecurityConstants.INNER);
        if (CheckRemoteServiceResultUtils.isCodeFail(gwjFinanceAccountDetailsR)) {
            throw new ServiceException("分类账流水查询失败");
        }
        if (CheckRemoteServiceResultUtils.isDataNull(gwjFinanceAccountDetailsR)) {
            throw new ServiceException("对账失败，未生成流水账单");
        }
        // 判断总账和分类账是否一致
        BigDecimal totalDetailMoney = gwjFinanceAccountDetailsR.getData().stream().map(GwjFinanceAccountDetail::getIncomeMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        if (!NumberUtil.equals(totalDetailMoney, totalMainMoney)) {
            throw new ServiceException("对账失败，实缴金额与应交金额不相等，请重新核对");
        }
        gwjDepositBusinessMoney.setStatus(GwjCheckAccountStatus.CHECK_SUCCESS.getCode());
        if (1 != gwjDepositBusinessMoneyService.updateGwjDepositBusinessMoney(gwjDepositBusinessMoney)) {
            throw new ServiceException("财务对账失败");
        }
        // 修改总账、分账对账状态
        if (!gwjDepositBusinessService.edisLedgerStatus(bizId, gwjDepositBusinessMoney.getStatus())) {
            throw new ServiceException("总账、分账对账状态修改失败");
        }
    }

    /**
     * 分摊金额统计-选中的
     *
     * @param gwjAllocatedAmountRequest 请求参数
     */
    @Override
    public GwjAllocatedAmountDTO allocatedAmount(GwjAllocatedAmountRequest gwjAllocatedAmountRequest) {
        GwjDepositBusiness gwjDepositBusiness = gwjDepositBusinessService.selectGwjDepositBusinessByBizId(gwjAllocatedAmountRequest.getBizId());
        if (ObjectUtil.isNull(gwjDepositBusiness)) {
            throw new ServiceException("查无业务信息");
        }
        // 统计总的数据
        List<GwjFundsSplitBusinessHouseDTO> gwjDepositBusinessHouses = gwjDepositBusinessHouseService.selectGwjDepositBusinessHouseWithBuildNameList(new GwjFundsSplitBusinessHouseRequest() {
            {
                setSelectFlag(GwjBusinessHouseStatus.CONFIRM.getCode());
                setBizId(gwjAllocatedAmountRequest.getBizId());
                if (StringUtils.isNotBlank(gwjAllocatedAmountRequest.getBuildCodeStr())) {
                    setBuildCodes(Convert.toStrArray(gwjAllocatedAmountRequest.getBuildCodeStr()));
                }
            }
        });
        if (StringUtils.isNotEmpty(gwjDepositBusinessHouses)) {
            BigDecimal totalActualSize = gwjDepositBusinessHouses.stream().filter(h -> StringUtils.isNotNull(h.getActualSize())).map(GwjFundsSplitBusinessHouseDTO::getActualSize).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal totalDepositSize = gwjDepositBusinessHouses.stream().filter(h -> StringUtils.isNotNull(h.getDepositSize())).map(GwjFundsSplitBusinessHouseDTO::getDepositSize).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal totalForecastSize = gwjDepositBusinessHouses.stream().filter(h -> StringUtils.isNotNull(h.getForecastSize())).map(GwjFundsSplitBusinessHouseDTO::getForecastSize).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal totalAllocationMoney = gwjDepositBusinessHouses.stream().filter(h -> StringUtils.isNotNull(h.getDepositMoney())).map(GwjFundsSplitBusinessHouseDTO::getDepositMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal totalAllocationLackMoney = gwjDepositBusinessHouses.stream().filter(h -> StringUtils.isNotNull(h.getLackMoney())).map(GwjFundsSplitBusinessHouseDTO::getLackMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
            // 查询业务金额
            GwjDepositBusinessMoney gwjDepositBusinessMoney = gwjDepositBusinessMoneyService.selectGwjDepositBusinessMoneyByBizId(gwjAllocatedAmountRequest.getBizId());
            return new GwjAllocatedAmountDTO() {
                {
                    setTotalActualSize(totalActualSize);
                    setTotalDepositSize(totalDepositSize);
                    setTotalForecastSize(totalForecastSize);
                    setTotalOwner(gwjDepositBusinessHouses.size());
                    setTotalAllocationMoney(totalAllocationMoney.add(totalAllocationLackMoney));
                    setTotalIncomeMoney(StringUtils.isNotNull(gwjDepositBusinessMoney) ? gwjDepositBusinessMoney.getTotalMoney() : BigDecimal.ZERO);
                }
            };
        } else {
            return new GwjAllocatedAmountDTO();
        }
    }

    /**
     * 分摊金额统计-选中的
     *
     * @param gwjAllocatedAmountRequest 请求参数
     */
    @Override
    public GwjAllocatedAmountScreeningDTO allocatedAmountScreening(GwjAllocatedAmountRequest gwjAllocatedAmountRequest) {
        GwjDepositBusiness gwjDepositBusiness = gwjDepositBusinessService.selectGwjDepositBusinessByBizId(gwjAllocatedAmountRequest.getBizId());
        if (ObjectUtil.isNull(gwjDepositBusiness)) {
            throw new ServiceException("查无业务信息");
        }
        // 统计总的数据
        List<GwjFundsSplitBusinessHouseDTO> gwjDepositBusinessHouses = gwjDepositBusinessHouseService.selectGwjDepositBusinessHouseWithBuildNameList(new GwjFundsSplitBusinessHouseRequest() {
            {
                setSelectFlag(GwjBusinessHouseStatus.CONFIRM.getCode());
                setBizId(gwjAllocatedAmountRequest.getBizId());
                if (StringUtils.isNotBlank(gwjAllocatedAmountRequest.getBuildCodeStr())) {
                    setBuildCodes(Convert.toStrArray(gwjAllocatedAmountRequest.getBuildCodeStr()));
                }
                if (StringUtils.isNotBlank(gwjAllocatedAmountRequest.getRoomNum())) {
                    setRoomNum(gwjAllocatedAmountRequest.getRoomNum());
                }
                if (StringUtils.isNotBlank(gwjAllocatedAmountRequest.getUseType())) {
                    setUseType(gwjAllocatedAmountRequest.getUseType());
                }
            }
        });
        if (StringUtils.isNotEmpty(gwjDepositBusinessHouses)) {
            BigDecimal screeningTotalActualSize = gwjDepositBusinessHouses.stream().filter(h -> StringUtils.isNotNull(h.getActualSize())).map(GwjFundsSplitBusinessHouseDTO::getActualSize).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal screeningTotalDepositSize = gwjDepositBusinessHouses.stream().filter(h -> StringUtils.isNotNull(h.getDepositSize())).map(GwjFundsSplitBusinessHouseDTO::getDepositSize).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal screeningTotalForecastSize = gwjDepositBusinessHouses.stream().filter(h -> StringUtils.isNotNull(h.getForecastSize())).map(GwjFundsSplitBusinessHouseDTO::getForecastSize).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal screeningTotalAllocationMoney = gwjDepositBusinessHouses.stream().filter(h -> StringUtils.isNotNull(h.getDepositMoney())).map(GwjFundsSplitBusinessHouseDTO::getDepositMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal screeningTotalAllocationLackMoney = gwjDepositBusinessHouses.stream().filter(h -> StringUtils.isNotNull(h.getLackMoney())).map(GwjFundsSplitBusinessHouseDTO::getLackMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
            return new GwjAllocatedAmountScreeningDTO() {
                {
                    setScreeningTotalActualSize(screeningTotalActualSize);
                    setScreeningTotalDepositSize(screeningTotalDepositSize);
                    setScreeningTotalForecastSize(screeningTotalForecastSize);
                    setScreeningTotalOwner(gwjDepositBusinessHouses.size());
                    setScreeningTotalAllocationMoney(screeningTotalAllocationMoney.add(screeningTotalAllocationLackMoney));
                }
            };
        } else {
            return new GwjAllocatedAmountScreeningDTO();
        }
    }

    /**
     * 获取小区分户清册头部详情
     *
     * @param bizId 业务ID
     * @return /
     */
    @Override
    public GwjFundsSplitHouseholdRecordHeadDTO getHouseholdRecordDetail(Long bizId) {
        GwjDepositBusiness gwjDepositBusiness = gwjDepositBusinessService.selectGwjDepositBusinessByBizId(bizId);
        if (ObjectUtil.isNull(gwjDepositBusiness)) {
            throw new ServiceException("查无业务信息");
        }
        GwjFundsSplitHouseholdRecordHeadDTO headDTO = new GwjFundsSplitHouseholdRecordHeadDTO();
        // 查询业务小区
        GwjDepositBusinessCommunity gwjDepositBusinessCommunity = gwjDepositBusinessCommunityService.selectGwjDepositBusinessCommunityByBizId(bizId);
        if (StringUtils.isNotNull(gwjDepositBusinessCommunity)) {
            headDTO.setBizCommunityName(gwjDepositBusinessCommunity.getCommunityName());
        }
        // 查业务楼栋
        List<GwjDepositBusinessBuild> gwjDepositBusinessBuilds = gwjDepositBusinessBuildService.selectGwjDepositBusinessBuildListByBizId(bizId);
        if (StringUtils.isNotEmpty(gwjDepositBusinessBuilds)) {
            List<String> buildNames = gwjDepositBusinessBuilds.stream().map(GwjBaseBusinessBuild::getBuildName).collect(Collectors.toList());
            headDTO.setBuildNames(StringUtils.join(buildNames, ","));
        }
        // 统计总的数据
        List<GwjDepositBusinessHouse> gwjDepositBusinessHouses = gwjDepositBusinessHouseService.selectGwjDepositBusinessHouseList(new GwjDepositBusinessHouse() {
            {
                setSelectFlag(GwjBusinessHouseStatus.CONFIRM.getCode());
                setBizId(bizId);
            }
        });
        if (StringUtils.isNotEmpty(gwjDepositBusinessHouses)) {
            BigDecimal totalActualSize = gwjDepositBusinessHouses.stream().map(GwjDepositBusinessHouse::getActualSize).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal totalAllocationMoney = gwjDepositBusinessHouses.stream().map(GwjDepositBusinessHouse::getDepositMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
            // 查询业务金额
            GwjDepositBusinessMoney gwjDepositBusinessMoney = gwjDepositBusinessMoneyService.selectGwjDepositBusinessMoneyByBizId(bizId);
            headDTO.setTotalActualSize(totalActualSize);
            headDTO.setTotalAllocationMoney(totalAllocationMoney);
            headDTO.setTotalOwner(gwjDepositBusinessHouses.size());
            headDTO.setTotalIncomeMoney(StringUtils.isNotNull(gwjDepositBusinessMoney) ? gwjDepositBusinessMoney.getTotalMoney() : BigDecimal.ZERO);
        }
        return headDTO;
    }

    /**
     * 导入业务房屋信息
     *
     * @param file  业务房屋文件
     * @param bizId 业务ID
     * @return /
     * @throws Exception /
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importGwjDepositBusinessHouse(MultipartFile file, Long bizId) throws Exception {
        // 验证是否有操作权限
        GwjDepositBusiness gwjDepositBusiness = gwjDepositBusinessService.checkPermission(bizId);
        ExcelUtil<GwjDepositBusinessHouseExcelVo> util = new ExcelUtil<>(GwjDepositBusinessHouseExcelVo.class);
        List<GwjDepositBusinessHouseExcelVo> gwjDepositBusinessHouses = util.importExcel(file.getInputStream());
        if (StringUtils.isEmpty(gwjDepositBusinessHouses)) {
            throw new ServiceException("导入房屋数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        for (GwjDepositBusinessHouse bh : GwjConvertUtil.convertList(gwjDepositBusinessHouses, GwjDepositBusinessHouse.class)) {
            if (StringUtils.isNull(bh)) {
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、导入数据未发现房屋编号 ");
            } else {
                GwjDepositBusinessHouse checkBh = gwjDepositBusinessHouseService.selectGwjDepositBusinessHouseByHouseCodeAndBizId(bh.getHouseCode(), bizId);
                if (StringUtils.isNotNull(checkBh)) {
                    checkBh.setDepositMoney(StringUtils.isNull(bh.getDepositMoney()) ? BigDecimal.ZERO : bh.getDepositMoney());
                    checkBh.setDepositSize(StringUtils.isNull(bh.getDepositSize()) ? BigDecimal.ZERO : bh.getDepositSize());
                    checkBh.setCalculateTypeId(GwjConstants.IMPORT_HOUSE_CALCULATE_ID);
                    checkBh.setCalculateVal(StringUtils.isNull(bh.getCalculateVal()) ? BigDecimal.ZERO : bh.getCalculateVal());
                    successNum++;
                    if (1 != gwjDepositBusinessHouseService.updateGwjDepositBusinessHouse(checkBh)) {
                        throw new ServiceException("资金分户初始化更新房屋数据失败");
                    }
                } else {
                    failureNum++;
                    failureMsg.append("<br/>").append(failureNum).append("、房屋编号： ").append(bh.getHouseId()).append(" 不存在");
                }
            }

        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        // 重新统计实际面积和实际金额
        // 查询业务金额
        GwjDepositBusinessMoney gwjDepositBusinessMoney = gwjDepositBusinessMoneyService.selectGwjDepositBusinessMoneyByBizId(bizId);
        List<GwjDepositBusinessHouse> gwjDepositBusinessHousesNew = gwjDepositBusinessHouseService.selectGwjDepositBusinessHouseListByBizIdAndSelectFlag(bizId, GwjBusinessHouseStatus.CONFIRM.getCode());
        BigDecimal factMoney = gwjDepositBusinessHousesNew.stream().map(GwjDepositBusinessHouse::getDepositMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal factSize = gwjDepositBusinessHousesNew.stream().map(GwjDepositBusinessHouse::getActualSize).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal lackMoney = gwjDepositBusinessHousesNew.stream().map(GwjDepositBusinessHouse::getLackMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        gwjDepositBusinessMoney.setFactMoney(factMoney.add(lackMoney));
        gwjDepositBusinessMoney.setFactSize(factSize);
        gwjDepositBusinessMoney.setTotalOwner(Convert.toLong(gwjDepositBusinessHousesNew.size()));
        if (1 != gwjDepositBusinessMoneyService.updateGwjDepositBusinessMoney(gwjDepositBusinessMoney)) {
            throw new ServiceException("资金分户初始化更新业务金额失败");
        }
        // 修改业务差额
        gwjDepositBusiness.setLackMoney(gwjDepositBusinessMoney.getTotalMoney().subtract(gwjDepositBusinessMoney.getFactMoney()));
        if (1 != gwjDepositBusinessService.updateGwjDepositBusiness(gwjDepositBusiness)) {
            throw new ServiceException("资金分户初始化更新业务失败");
        }
        return "恭喜您，数据已全部导入成功！共 " + successNum + " 条！";
    }

    /**
     * 校验步骤
     *
     * @param stepId         步骤主键
     * @param stepConfigInfo 操作信息
     * @return /
     */
    private Boolean checkStepConfigInfo(Long stepId, String stepConfigInfo) {
        R<List<String>> configInfosR = remoteGwjConfigService.selectGwjConfStepConfigInfoCodeListByBizFlagId(stepId, SecurityConstants.INNER);
        if (!CheckRemoteServiceResultUtils.isSuccessWithData(configInfosR)) {
            throw new ServiceException("步骤配置查询失败");
        }
        if (!StringUtils.containsAny(configInfosR.getData(), stepConfigInfo)) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

}
